#Region "Imports"
Imports MatrixDataStructures
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Imports twoDMatrixLibrary
Imports Crownwood.Magic.Common
Imports Crownwood.Magic.Docking
Imports CommonNamespace
#End Region

#Region "Thread Safe Delegates"
Public Delegate Sub UpdateAnatomyVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
Public Delegate Sub UpdateDiffusionVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
Public Delegate Sub UpdatefMRIVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
Public Delegate Sub UpdatePerfusionVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
#End Region


Public Class FormMain
    Inherits System.Windows.Forms.Form
    Private _license As System.ComponentModel.License = Nothing

#Region "Memory Release"
    Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32
    Private Declare Function EmptyWorkingSet Lib "psapi.dll" (ByVal hProcess As IntPtr) As Int32

    Friend Sub ReleaseMemory()
        Try
            GC.Collect()
            GC.WaitForPendingFinalizers()
            If Environment.OSVersion.Platform = PlatformID.Win32NT Then
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1)
            End If
            EmptyWorkingSet(Process.GetCurrentProcess().Handle)
        Catch
        End Try
    End Sub
#End Region

#Region "Declaration of Objects and Variables"
    Public CurrentActiveDisplay As MainForm.DisplayType = MainForm.DisplayType.Coronal
    Public CurrentActiveSlice As Integer = 0
    Dim EachDatasetInNewWindow As Boolean = True
    Public IsFACalculated As Boolean = False
    Dim IndependentViews As Boolean = True
    Dim VolumeBox As MainForm
    Public DTIClass As frmDTIParamertersSet
    Public AnatomyVolume, PerfusionVolume, fMRIVolume, FAVolume As SingleVolume
    Public DiffusionVolume As MultiVolume
    Public WithEvents AnatomyDisplay, fMRIDisplay, DiffusionDisplay, PerfusionDisplay As MainForm
    Dim CurrentProcessDescription As String
    Dim PerfusionLoader As PerfusionParRecLoader
    Dim roiA, roiD, roiP, roiF As ROIEditor

#End Region

#Region "Window Display Properties"
    Public CommonWindowSize As Size
    Public AnatomyLocation, fMRILocation, DWILocation, PerfusionLocation As Point
#End Region

#Region "Other Methods and Event Handlers"
    <STAThread()> Friend Sub Main()
        ' Create an instance of the licensed application
        Dim app As FormMain = Nothing
        Try
            ' This will throw a LicenseException if the 
            ' license is invalid... If we get an exception,
            ' "app" will remain null and the Run() method
            ' (below) will not be executed...
            app = New FormMain
        Catch ex As Exception
            ' Catch any error, but especially licensing errors...
            Dim strErr As String = String.Format("Error executing application: '{0}'", ex.Message)
            MessageBox.Show(strErr, "VB RegistryLicensedApplication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        If Not app Is Nothing Then
            Application.Run(app)
        End If
    End Sub
#Region "thread safe volume display functions"
    Private Sub UpdateAnatomyVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
        If AnatomyDisplay.InvokeRequired Then
            ' Invoke the delegate.
            AnatomyDisplay.Invoke(New UpdateAnatomyVolume(AddressOf AnatomyDisplay.OpenFile), New Object() {volume, label, ismatrix, ismatrixd})
        Else
            'same thread or it was delegated back to main thread, just update
            AnatomyDisplay.OpenFile(volume, label, ismatrix, ismatrixd)
        End If
    End Sub
    Private Sub UpdateDWIVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
        If DiffusionDisplay.InvokeRequired Then
            ' Invoke the delegate.
            DiffusionDisplay.Invoke(New UpdateAnatomyVolume(AddressOf DiffusionDisplay.OpenFile), New Object() {volume, label, ismatrix, ismatrixd})
        Else
            'same thread or it was delegated back to main thread, just update
            DiffusionDisplay.OpenFile(volume, label, ismatrix, ismatrixd)
        End If
    End Sub
    Private Sub UpdatePerfusionVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
        If PerfusionDisplay.InvokeRequired Then
            ' Invoke the delegate.
            PerfusionDisplay.Invoke(New UpdateAnatomyVolume(AddressOf PerfusionDisplay.OpenFile), New Object() {volume, label, ismatrix, ismatrixd})
        Else
            'same thread or it was delegated back to main thread, just update
            PerfusionDisplay.OpenFile(volume, label, ismatrix, ismatrixd)
        End If
    End Sub
    Private Sub UpdatefMRIVolume(ByVal volume As SingleVolume, ByVal label As String, ByVal ismatrix As Boolean, ByVal ismatrixd As Boolean)
        If fMRIDisplay.InvokeRequired Then
            ' Invoke the delegate.
            fMRIDisplay.Invoke(New UpdateAnatomyVolume(AddressOf fMRIDisplay.OpenFile), New Object() {volume, label, ismatrix, ismatrixd})
        Else
            'same thread or it was delegated back to main thread, just update
            fMRIDisplay.OpenFile(volume, label, ismatrix, ismatrixd)
        End If
    End Sub
#End Region
    Dim _dockingmanager As Crownwood.Magic.Docking.DockingManager
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        Me.IsMdiContainer = True


    End Sub
    Private Sub SwitchToFA(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ' MsgBox("FA Calculation Complete!", MsgBoxStyle.OkOnly)
        If Me.LoadFAVolumeAutomaticallyToolStripMenuItem.Checked = False Then
            'If MsgBox(" FA Calculation Complete !" & vbNewLine & _
            '          " Load FA Volume & discard" & vbNewLine & _
            '          " Diffusion Weighted Data ?", MsgBoxStyle.OkCancel, "FA Calculation") = MsgBoxResult.Ok Then
            Me.FAVolume = New SingleVolume
            Me.FAVolume.FOV = Me.DiffusionVolume.FOV
            Me.FAVolume.Center = Me.DiffusionVolume.Center
            Me.FAVolume.MatrixD = DTIClass.ReturnFA
            Me.IsFACalculated = True
            FAVolume.Matrix = New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(0))

            UpdateDWIVolume(New SingleVolume(DTIClass.ReturnFA, FAVolume), "FA", False, True)

            Me.DiffusionVolume.Matrix.Dispose()
            '   End If
        ElseIf Me.LoadFAVolumeAutomaticallyToolStripMenuItem.Checked = True Then
            UpdateDWIVolume(New SingleVolume(DTIClass.ReturnFA, FAVolume), "Fractional Anisotrophy", False, True)
            Me.FAVolume = New SingleVolume
            Me.FAVolume.FOV = Me.DiffusionVolume.FOV
            Me.FAVolume.Center = Me.DiffusionVolume.Center
            Me.FAVolume.MatrixD = DTIClass.ReturnFA
            Me.IsFACalculated = True
            If MsgBox("Dispose Original DWI Data after FA Calculation?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                Me.DiffusionVolume.Matrix.Dispose()
            End If
            End If
    End Sub
    Private Sub contentPanel_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles contentPanel.Paint

        GC.Collect()
        If contentPanel.Dock = DockStyle.Fill Then
            contentPanel.Hide()
            Dim h As Integer = contentPanel.Height
            CommonWindowSize = New Size(CInt(Me.contentPanel.Width / 2) - 5, CInt(h / 2) - 5)
            AnatomyDisplay = New MainForm
            DiffusionDisplay = New MainForm
            fMRIDisplay = New MainForm
            PerfusionDisplay = New MainForm
            AnatomyDisplay.Size = CommonWindowSize

            PerfusionDisplay.Size = CommonWindowSize
            fMRIDisplay.Size = CommonWindowSize
            PerfusionDisplay.Size = CommonWindowSize

            _dockingmanager = New DockingManager(Me, VisualStyle.IDE)
            Dim notepad1 As Content = _dockingmanager.Contents.Add(PerfusionDisplay, "Perfusion Data", _internalimages, 1)
            Dim notepad3 As Content = _dockingmanager.Contents.Add(DiffusionDisplay, "DWI/DTI Data", _internalimages, 1)
            Dim notepad4 As Content = _dockingmanager.Contents.Add(fMRIDisplay, "fMRI Data", _internalimages, 1)
            Dim notepad5 As Content = _dockingmanager.Contents.Add(AnatomyDisplay, "Anatomy Data", _internalimages, 1)
            notepad1.DisplaySize = CommonWindowSize
            notepad3.DisplaySize = CommonWindowSize
            notepad4.DisplaySize = CommonWindowSize
            notepad5.DisplaySize = CommonWindowSize
            notepad1.DockingManager.InsideFill = True
            notepad4.DockingManager.InsideFill = True
            notepad3.DockingManager.InsideFill = True
            notepad5.DockingManager.InsideFill = True
            Dim wc As WindowContent = _dockingmanager.AddContentWithState(notepad1, State.DockRight)
            wc.BackColor = Color.Black
            _dockingmanager.AddContentToZone(notepad3, wc.ParentZone, 0)
            Dim wc2 As WindowContent = _dockingmanager.AddContentWithState(notepad4, State.DockLeft)
            _dockingmanager.AddContentToZone(notepad5, wc2.ParentZone, 0)
            wc2.BackColor = Color.Black
            _dockingmanager.ResizeBarColor = Color.Black
            _dockingmanager.ActiveColor = Color.Black
            _dockingmanager.PlainTabBorder = True
            _dockingmanager.BackColor = Color.Gray
            _dockingmanager.ActiveTextColor = Color.Peru
            _dockingmanager.InactiveTextColor = Color.Black
            _dockingmanager.InnerControl = Nothing
            _dockingmanager.InsideFill = True
        Else
            contentPanel.Dock = DockStyle.Fill
        End If
        ReleaseMemory()
    End Sub
#End Region

    Public Function GetFirstBit(ByVal Val As MainForm.DisplayType) As String
        Select Case Val
            Case MainForm.DisplayType.Coronal
                Return "c"
            Case MainForm.DisplayType.Sagittal
                Return "s"
            Case MainForm.DisplayType.Transverse
                Return "t"
            Case Else
                Return "t"
        End Select
    End Function

#Region "Event Handlers"

    Public Sub AnatomyBaseDataFiltered(ByVal Sender As Object, ByVal e As EventArgs)
        GenerateConstants(AnatomyVolume.Matrix)
        AnatomyVolume.Matrix = GetNewUnScaledDataInt16(CType(Sender, Short(,,)))
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
        If AnatomyDisplay IsNot Nothing And AnatomyVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < AnatomyVolume.Matrix.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < AnatomyVolume.Matrix.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < AnatomyVolume.Matrix.y) Then
                AnatomyDisplay.ChangeCurrentSliceInfo(Mid(GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub
    Public Sub fMRIBaseDataFiltered(ByVal Sender As Object, ByVal e As EventArgs)
        GenerateConstants(fMRIVolume.Matrix)
        fMRIVolume.Matrix = GetNewUnScaledDataInt16(CType(Sender, Short(,,)))
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
        If fMRIDisplay IsNot Nothing And fMRIVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < fMRIVolume.Matrix.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < fMRIVolume.Matrix.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < fMRIVolume.Matrix.y) Then
                fMRIDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub
    Public Sub DiffusionBaseDataFiltered(ByVal Sender As Object, ByVal e As EventArgs)
        If Me.IsFACalculated = True Then
            GenerateConstants(FAVolume.MatrixD)
            FAVolume.MatrixD = GetNewUnScaledDataSng(CType(Sender, Short(,,)))
            UpdateDWIVolume(FAVolume, "FA", False, True)
            If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < FAVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < FAVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < FAVolume.MatrixD.y) Then
                    DiffusionDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
                End If
            End If
        Else
            MsgBox("Filters are not allowed on 4D Data. Please compute FA values first.")
        End If

    End Sub
    Public Sub PerfusionBaseDataFiltered(ByVal Sender As Object, ByVal e As EventArgs)
        GenerateConstants(PerfusionVolume.MatrixD)
        PerfusionVolume.MatrixD = GetNewUnScaledDataSng(CType(Sender, Short(,,)))
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
        If PerfusionDisplay IsNot Nothing And PerfusionVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.y) Then
                PerfusionDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub

    Public Sub MouseMovedOnAnatomy(ByVal sender As Object, ByVal e As EventArgs)
        Dim highlightlocation As Point = CType(sender, Point)
        Dim CurrentZoom As Single = (CType(e, FormStateEventArgs)).zoom
        Dim CurrentVScroll As Single = (CType(e, FormStateEventArgs)).VerticalScrollValue
        Dim CurrentHScroll As Single = (CType(e, FormStateEventArgs)).HorizontalScrollValue
        Dim temp As Double = 0

        'If AnatomyDisplay IsNot Nothing And AnatomyVolume IsNot Nothing Then
        '    If AnatomyDisplay.CurrentActiveDisplay = Me.CurrentActiveDisplay Then
        '        Select Case Me.CurrentActiveDisplay
        '            Case MainForm.DisplayType.Transverse
        '                Try
        '                    temp = (AnatomyVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Coronal
        '                Try
        '                    temp = (AnatomyVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Sagittal
        '                Try
        '                    temp = (AnatomyVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '        End Select
        '        AnatomyDisplay.HighlightPointRed(highlightlocation.X, highlightlocation.Y, temp, False)
        '    End If
        'End If
        If Me.IndependentViews = False Then
            UpdateAllWhenMouseIsMoved(highlightlocation.X, highlightlocation.Y, CurrentZoom, CurrentVScroll, CurrentHScroll)
        End If
    End Sub
    Public Sub MouseMovedOnfMRI(ByVal sender As Object, ByVal e As EventArgs)
        Dim highlightlocation As Point = CType(sender, Point)
        Dim CurrentZoom As Single = (CType(e, FormStateEventArgs)).zoom
        Dim CurrentVScroll As Single = (CType(e, FormStateEventArgs)).VerticalScrollValue
        Dim CurrentHScroll As Single = (CType(e, FormStateEventArgs)).HorizontalScrollValue
        Dim temp As Double = 0
        'If fMRIDisplay IsNot Nothing And fMRIVolume IsNot Nothing Then
        '    If fMRIDisplay.CurrentActiveDisplay = Me.CurrentActiveDisplay Then
        '        Select Case Me.CurrentActiveDisplay
        '            Case MainForm.DisplayType.Transverse
        '                Try
        '                    temp = (fMRIVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Coronal
        '                Try
        '                    temp = (fMRIVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Sagittal
        '                Try
        '                    temp = (fMRIVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '        End Select
        '        fMRIDisplay.HighlightPointRed(highlightlocation.X, highlightlocation.Y, temp, False)
        '    End If
        'End If
        If Me.IndependentViews = False Then
            UpdateAllWhenMouseIsMoved(highlightlocation.X, highlightlocation.Y, CurrentZoom, CurrentVScroll, CurrentHScroll)
        End If

    End Sub
    Public Sub MouseMovedOnDiffusion(ByVal sender As Object, ByVal e As EventArgs)
        Dim highlightlocation As Point = CType(sender, Point)
        Dim CurrentZoom As Single = (CType(e, FormStateEventArgs)).zoom
        Dim CurrentVScroll As Single = (CType(e, FormStateEventArgs)).VerticalScrollValue
        Dim CurrentHScroll As Single = (CType(e, FormStateEventArgs)).HorizontalScrollValue
        Dim temp As Double = 0

        'If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing And Me.IsFACalculated = True Then
        '    If DiffusionDisplay.CurrentActiveDisplay = Me.CurrentActiveDisplay Then
        '        Select Case Me.CurrentActiveDisplay
        '            Case MainForm.DisplayType.Transverse
        '                Try
        '                    temp = Math.Round((FAVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y)), 4)
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Coronal
        '                Try
        '                    temp = Math.Round((FAVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y)), 4)
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '            Case MainForm.DisplayType.Sagittal
        '                Try
        '                    temp = Math.Round((FAVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y)), 4)
        '                Catch ex As Exception
        '                    'mouse outside image coordinates
        '                End Try
        '        End Select
        '        DiffusionDisplay.HighlightPointRed(highlightlocation.X, highlightlocation.Y, temp, False)
        '    Else

        '    End If

        'End If
        If Me.IndependentViews = False Then
            UpdateAllWhenMouseIsMoved(highlightlocation.X, highlightlocation.Y, CurrentZoom, CurrentVScroll, CurrentHScroll)
        End If
    End Sub
    Public Sub MouseMovedOnPerfusion(ByVal sender As Object, ByVal e As EventArgs)
        If PerfusionVolume.MatrixD IsNot Nothing Then
            Dim highlightlocation As Point = CType(sender, Point)
            Dim CurrentZoom As Single = (CType(e, FormStateEventArgs)).zoom
            Dim CurrentVScroll As Single = (CType(e, FormStateEventArgs)).VerticalScrollValue
            Dim CurrentHScroll As Single = (CType(e, FormStateEventArgs)).HorizontalScrollValue
            Dim temp As Double = 0
            'If PerfusionDisplay IsNot Nothing And PerfusionVolume IsNot Nothing Then
            '    If PerfusionDisplay.CurrentActiveDisplay = Me.CurrentActiveDisplay Then
            '        Select Case Me.CurrentActiveDisplay
            '            Case MainForm.DisplayType.Transverse
            '                Try
            '                    temp = (PerfusionVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
            '                Catch ex As Exception
            '                    'mouse outside image coordinates
            '                End Try
            '            Case MainForm.DisplayType.Coronal
            '                Try
            '                    temp = (PerfusionVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
            '                Catch ex As Exception
            '                    'mouse outside image coordinates
            '                End Try
            '            Case MainForm.DisplayType.Sagittal
            '                Try
            '                    temp = (PerfusionVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)(highlightlocation.X, highlightlocation.Y))
            '                Catch ex As Exception
            '                    'mouse outside image coordinates
            '                End Try
            '        End Select
            '        PerfusionDisplay.HighlightPointRed(highlightlocation.X, highlightlocation.Y, temp, False)
            '    End If
            'End If
            If Me.IndependentViews = False Then
                UpdateAllWhenMouseIsMoved(highlightlocation.X, highlightlocation.Y, CurrentZoom, CurrentVScroll, CurrentHScroll)
            End If
        End If
    End Sub
    Public Sub UpdateAllWhenMouseIsMoved(ByVal HighLightLocationX As Integer, ByVal HighlightLocationY As Integer, ByVal CurrentZoom As Single, ByVal CurrentVScroll As Single, ByVal CurrentHScroll As Single)

        Dim valueA, valueF, valueD, valueP As Single
        Select Case Me.CurrentActiveDisplay
            Case MainForm.DisplayType.Transverse
                If AnatomyDisplay IsNot Nothing And AnatomyVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= AnatomyVolume.Matrix.z Then valueA = CSng(IIf(AnatomyVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And AnatomyVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, AnatomyVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= FAVolume.MatrixD.z Then valueD = CSng(IIf(FAVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And FAVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, FAVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If PerfusionDisplay IsNot Nothing And PerfusionVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= PerfusionVolume.MatrixD.z Then valueP = CSng(IIf(PerfusionVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And PerfusionVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, PerfusionVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If fMRIDisplay IsNot Nothing And fMRIVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= fMRIVolume.Matrix.z Then valueF = CSng(IIf(fMRIVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And fMRIVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, fMRIVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
            Case MainForm.DisplayType.Coronal
                If AnatomyDisplay IsNot Nothing And AnatomyVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= AnatomyVolume.Matrix.y Then valueA = CSng(IIf(AnatomyVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And AnatomyVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, AnatomyVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= FAVolume.MatrixD.y Then valueD = CSng(IIf(FAVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And FAVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, FAVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If PerfusionDisplay IsNot Nothing And PerfusionVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= PerfusionVolume.MatrixD.y Then valueP = CSng(IIf(PerfusionVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And PerfusionVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, PerfusionVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If fMRIDisplay IsNot Nothing And fMRIVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= fMRIVolume.Matrix.z Then valueF = CSng(IIf(fMRIVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And fMRIVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, fMRIVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
            Case MainForm.DisplayType.Sagittal
                If AnatomyDisplay IsNot Nothing And AnatomyVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= AnatomyVolume.Matrix.x Then valueA = CSng(IIf(AnatomyVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And AnatomyVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, AnatomyVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= FAVolume.MatrixD.x Then valueD = CSng(IIf(FAVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(0) + 1 >= HighLightLocationX And FAVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, FAVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If PerfusionDisplay IsNot Nothing And PerfusionVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= PerfusionVolume.MatrixD.x Then valueP = CSng(IIf(PerfusionVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(0) >= HighLightLocationX And PerfusionVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, PerfusionVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
                If fMRIDisplay IsNot Nothing And fMRIVolume IsNot Nothing Then
                    If Me.CurrentActiveSlice <= fMRIVolume.Matrix.x Then valueF = CSng(IIf(fMRIVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(0) >= HighLightLocationX And fMRIVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice).GetUpperBound(1) >= HighlightLocationY, fMRIVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)(HighLightLocationX, HighlightLocationY), -Math.PI))
                End If
        End Select

        'update zoom and scrollbars
        If AnatomyDisplay IsNot Nothing Then
            AnatomyDisplay.ChangeCurrentImageZoom(CurrentZoom)
            '    AnatomyDisplay.ManuallyScroll(CurrentVScroll, CurrentHScroll)
            '  AnatomyDisplay.AmIOnSameSlice = False
            If valueA <> -Math.PI Then AnatomyDisplay.HighlightPointRed(HighLightLocationX, HighlightLocationY, valueA, True)
        End If
        If fMRIDisplay IsNot Nothing Then
            fMRIDisplay.ChangeCurrentImageZoom(CurrentZoom)
            '    fMRIDisplay.ManuallyScroll(CurrentVScroll, CurrentHScroll)
            ' fMRIDisplay.AmIOnSameSlice = False
            If valueF <> -Math.PI Then fMRIDisplay.HighlightPointRed(HighLightLocationX, HighlightLocationY, valueF, True)
        End If
        If DiffusionDisplay IsNot Nothing Then
            DiffusionDisplay.ChangeCurrentImageZoom(CurrentZoom)
            '   DiffusionDisplay.ManuallyScroll(CurrentVScroll, CurrentHScroll)
            'DiffusionDisplay.AmIOnSameSlice = False
            If valueD <> -Math.PI Then DiffusionDisplay.HighlightPointRed(HighLightLocationX, HighlightLocationY, valueD, True)
        End If
        If PerfusionDisplay IsNot Nothing Then
            PerfusionDisplay.ChangeCurrentImageZoom(CurrentZoom)
            '  PerfusionDisplay.ManuallyScroll(CurrentVScroll, CurrentHScroll)
            'PerfusionDisplay.AmIOnSameSlice = False
            If valueP <> -Math.PI Then PerfusionDisplay.HighlightPointRed(HighLightLocationX, HighlightLocationY, valueP, True)
        End If
    End Sub

    Public Sub CurrentSliceInformation(ByVal sender As Object, ByVal e As EventArgs)
        Dim sliceinfo As String = CType(sender, String)
        Select Case Mid(sliceinfo, 1, 1)
            Case "t"
                CurrentActiveDisplay = MainForm.DisplayType.Transverse
            Case "c"
                CurrentActiveDisplay = MainForm.DisplayType.Coronal
            Case "s"
                CurrentActiveDisplay = MainForm.DisplayType.Sagittal
        End Select
        CurrentActiveSlice = CInt(Mid(sliceinfo, 2, sliceinfo.Length - 1))
        If Me.IndependentViews = False Then
            If AnatomyVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < AnatomyVolume.Matrix.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < AnatomyVolume.Matrix.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < AnatomyVolume.Matrix.y) Then
                    AnatomyDisplay.ChangeCurrentSliceInfo(Mid(sliceinfo, 1, 1), CurrentActiveSlice)
                End If
            End If
            If fMRIVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < fMRIVolume.Matrix.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < fMRIVolume.Matrix.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < fMRIVolume.Matrix.y) Then
                    fMRIDisplay.ChangeCurrentSliceInfo(Mid(sliceinfo, 1, 1), CurrentActiveSlice)
                End If
            End If
            If FAVolume Is Nothing And DiffusionVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < DiffusionVolume.Matrix.k) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < DiffusionVolume.Matrix.i) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < DiffusionVolume.Matrix.j) Then
                    DiffusionDisplay.ChangeCurrentSliceInfo(Mid(sliceinfo, 1, 1), CurrentActiveSlice)
                End If
            End If
            If FAVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < FAVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < FAVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < FAVolume.MatrixD.y) Then
                    DiffusionDisplay.ChangeCurrentSliceInfo(Mid(sliceinfo, 1, 1), CurrentActiveSlice)
                End If
            End If
            If PerfusionVolume IsNot Nothing Then
                If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < PerfusionVolume.MatrixD.y) Then
                    PerfusionDisplay.ChangeCurrentSliceInfo(Mid(sliceinfo, 1, 1), CurrentActiveSlice)
                End If
            End If
        End If
    End Sub

    Public Sub AnatomySubjectInfoShow(ByVal sender As Object, ByVal e As EventArgs)
        If AnatomyVolume.HeaderFileName.Length > 4 Then
            Try
                Dim anatomysubject As New SubjectHeader(AnatomyVolume.HeaderFileName)
                anatomysubject.Show()

            Catch ex As Exception
                MsgBox("Loading Header Information from file failed.")
            End Try
        Else
            MsgBox("Subject information not found. Please load" & Chr(13) & Chr(10) & "RAW datasets to view subject information.", MsgBoxStyle.Information, "Subject Information")
        End If
    End Sub
    Public Sub fMRISubjectInfoShow(ByVal sender As Object, ByVal e As EventArgs)
        If fMRIVolume.HeaderFileName.Length > 4 Then
            Try
                Dim fmrisubject As New SubjectHeader(fMRIVolume.HeaderFileName)
                fmrisubject.Show()
            Catch ex As Exception
                MsgBox("Loading Header Information from file failed.")
            End Try
        Else
            MsgBox("Subject information not found. Please load" & Chr(13) & Chr(10) & "RAW datasets to view subject information.", MsgBoxStyle.Information, "Subject Information")
        End If
    End Sub
    Public Sub DiffusionSubjectInfoShow(ByVal sender As Object, ByVal e As EventArgs)
        If DiffusionVolume IsNot Nothing And Me.IsFACalculated = False Then
            Try
                Dim diffusionsubject As New SubjectHeader(DiffusionVolume.HeaderFileName)
                diffusionsubject.Show()
            Catch ex As Exception
                MsgBox("Loading Header Information from file failed.")
            End Try

        Else
            MsgBox("Subject information not found. Please load" & Chr(13) & Chr(10) & "RAW datasets to view subject information.", MsgBoxStyle.Information, "Subject Information")
        End If
    End Sub
    Public Sub PerfusionSubjectInfoShow(ByVal sender As Object, ByVal e As EventArgs)
        If PerfusionVolume.HeaderFileName.Length > 4 Then
            Try
                Dim perfusionsubject As New SubjectHeader(PerfusionVolume.HeaderFileName)
                perfusionsubject.Show()
            Catch ex As Exception
                MsgBox("Loading Header Information from file failed.")
            End Try
        Else
            MsgBox("Subject information not found. Please load" & Chr(13) & Chr(10) & "RAW datasets to view subject information.", MsgBoxStyle.Information, "Subject Information")
        End If
    End Sub
#End Region

#Region "Loaders"
    Private Sub NewAnatomyVolumeLoader(ByVal fileName As String)
        AnatomyVolume = New SingleVolume
        Dim fname As New System.IO.FileInfo(fileName)
        If fname.Extension = ".par" Or fname.Extension = ".PAR" Then
            Dim Loader As New SingleOptimizedParRecLoader(fileName)
            AnatomyVolume = Loader.GetData
        ElseIf fname.Extension = ".hdr" Or fname.Extension = ".HDR" Then
            AnatomyVolume = HdrImgReader.ReadFromHdrFile(fileName)
            If AnatomyVolume.Matrix Is Nothing Then
                AnatomyVolume.Matrix = AnatomyVolume.MatrixD.ReScaleToINT(AnatomyVolume.MatrixD, 0, 255)
                MsgBox("The anatomy data has been rescaled to fit display." + vbNewLine + _
                       "Please do not save this data directly.")
            End If
        End If
        AnatomyVolume.HeaderFileName = fileName
        If Me.EachDatasetInNewWindow = False Then
            VolumeBox.OpenFile(AnatomyVolume, "Anatomy", True, False)
        Else
            UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
            AddAnatomyHandles()
        End If
    End Sub

    Private Sub NewFMRIVolumeLoader(ByVal filename As String)
        fMRIVolume = HdrImgReader.ReadFromHdrFile(filename, OutPutType.int16)
        fMRIVolume.HeaderFileName = filename

        If Me.EachDatasetInNewWindow = False Then
            VolumeBox.OpenFile(fMRIVolume, "fMRI", True, False)
        Else
            UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
            AddfMRIHandles()
        End If

    End Sub
    Private Sub NewDWIVolumeLoader(ByVal fileName As String)
        Dim fname As New System.IO.FileInfo(fileName)
        DiffusionVolume = New MultiVolume
        If fname.Extension = ".HDR" Or fname.Extension = ".hdr" Then
            DiffusionVolume.Matrix = Nothing
            Dim files() As String = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(fileName))
            Dim validNameList As New System.Collections.SortedList
            For Each file As String In files
                Dim posindex As Integer = System.IO.Path.GetFileNameWithoutExtension(file).LastIndexOf("_")
                If posindex <= 1 Then Continue For
                If file.Substring(0, posindex - 1) = fileName.Substring(0, posindex - 1) And System.IO.Path.GetExtension(file).ToLower = ".hdr" Then
                    Dim filenumber As String = System.IO.Path.GetFileNameWithoutExtension(file)
                    filenumber = filenumber.Substring(posindex, filenumber.Length - (posindex))
                    filenumber = filenumber.Trim(CChar("_"))
                    validNameList.Add(Int32.Parse(filenumber), file)
                    '              MsgBox(filenumber & ":  " & file)
                End If
            Next
            Dim loadcounter As Integer = 0
            Dim ide As IDictionaryEnumerator = validNameList.GetEnumerator()
            While (ide.MoveNext())
                '          MsgBox(ide.Key.ToString() & ":" & ide.Value.ToString())
                Dim tempv As SingleVolume = HdrImgReader.ReadFromHdrFile(ide.Value.ToString(), OutPutType.int16)
                If DiffusionVolume.Matrix Is Nothing Then
                    DiffusionVolume.Matrix = New Matrix4DInt16(tempv.Matrix.x, tempv.Matrix.y, tempv.Matrix.z, validNameList.Count)
                    MsgBox("Diffusion Matrix initialized to : " & tempv.Matrix.x & "," & tempv.Matrix.y & "," & tempv.Matrix.z & "," & validNameList.Count)
                End If
                DiffusionVolume.Matrix.LoadVolume(loadcounter, tempv.Matrix.data)
                loadcounter += 1
            End While
        ElseIf fname.Extension = ".par" Or fname.Extension = ".PAR" Then
            Dim Loader As New MultipleOptimizedParRecLoader(fileName)
            DiffusionVolume = Loader.GetData
            DiffusionVolume.HeaderFileName = fileName
        End If

        Dim temp As New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(0))

        If Me.EachDatasetInNewWindow = False Then
            VolumeBox.OpenFile(New SingleVolume(temp, DiffusionVolume.FOV, DiffusionVolume.Center), "Diffusion", True, False)
        Else
            UpdateDWIVolume(New SingleVolume(temp, DiffusionVolume.FOV, DiffusionVolume.Center), "Diffusion", True, False)
            AddDiffusionHandles()
        End If
        temp.Dispose()
    End Sub
    Private Sub NewPerfusionVolumeLoader(ByVal filename As String)
        PerfusionVolume = New SingleVolume
        PerfusionLoader = New PerfusionParRecLoader(filename)

        PerfusionVolume.HeaderFileName = filename
        PerfusionVolume.Matrix = New Matrix3DInt16(PerfusionLoader.GetData.Matrix.ExtractVolume(0))
        PerfusionVolume.FOV = PerfusionLoader.GetData.FOV
        PerfusionVolume.Center = PerfusionLoader.GetData.Center
        PerfusionVolume.HeaderFileName = PerfusionLoader.GetData.HeaderFileName

        If Me.EachDatasetInNewWindow = False Then
            VolumeBox.OpenFile(PerfusionVolume, "Perfusion", True, False)
        Else
            UpdatePerfusionVolume(PerfusionVolume, "Perfusion", True, False)
            AddPerfusionHandles()
        End If

    End Sub
#End Region

#Region "Menu Butoon Programs"

    Private Sub ExitButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        If MsgBox("Are You Sure ?", MsgBoxStyle.YesNo, "Exit Metaview") = MsgBoxResult.Yes Then
            Me.Dispose()
            Application.Exit()
        End If
    End Sub

    Private Sub OpenEachToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenEachToolStripMenuItem.Click
        OpenEachToolStripMenuItem.Checked = Not OpenEachToolStripMenuItem.Checked
        If OpenEachToolStripMenuItem.Checked = True Then
            Me.EachDatasetInNewWindow = True
        Else
            Me.OpenEachToolStripMenuItem.Checked = False
            If VolumeBox Is Nothing Then
                VolumeBox = New MainForm
                VolumeBox.Show()
            End If
        End If

    End Sub

    Private Sub NavigateToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NavigateToolStripMenuItem.Click
        'Anatomy Always has to be loaded
        'Compare everything else to anatomy first
        If Me.NavigateToolStripMenuItem.Checked = True Then
            Me.NavigateToolStripMenuItem.Checked = False
            Me.IndependentViews = True
            Exit Sub
        End If

        If AnatomyVolume Is Nothing Then
            MsgBox("Anatomy Data is necessary to Conavigate between datasets!", MsgBoxStyle.Exclamation)
            NavigateToolStripMenuItem.Checked = False
            Exit Sub
        Else
            NavigateToolStripMenuItem.Checked = True
        End If
        'Otherwise
        If Me.NavigateToolStripMenuItem.Checked = True Then
            If fMRIVolume IsNot Nothing Then
                If fMRIVolume.Matrix.x <> AnatomyVolume.Matrix.x _
                Or fMRIVolume.Matrix.y <> AnatomyVolume.Matrix.y _
                Or fMRIVolume.Matrix.z <> AnatomyVolume.Matrix.z Then
                    MsgBox("fMRI Matrix size mismatch!", MsgBoxStyle.Exclamation)
                    NavigateToolStripMenuItem.Checked = False
                    Exit Sub
                End If
            End If
            If FAVolume IsNot Nothing And IsFACalculated = True Then
                If FAVolume.MatrixD.x <> AnatomyVolume.Matrix.x _
                Or FAVolume.MatrixD.y <> AnatomyVolume.Matrix.y _
                Or FAVolume.MatrixD.z <> AnatomyVolume.Matrix.z Then
                    MsgBox("FA Matrix size mismatch!", MsgBoxStyle.Exclamation)
                    NavigateToolStripMenuItem.Checked = False
                    Exit Sub
                End If
            ElseIf DiffusionVolume IsNot Nothing And IsFACalculated = False Then
                MsgBox("FA Needs to be calculated before creating Composite Maps!")
                NavigateToolStripMenuItem.Checked = False
                Exit Sub
            End If
            If PerfusionVolume IsNot Nothing Then
                If PerfusionVolume.MatrixD.x <> AnatomyVolume.Matrix.x _
                Or PerfusionVolume.MatrixD.y <> AnatomyVolume.Matrix.y _
                Or PerfusionVolume.MatrixD.z <> AnatomyVolume.Matrix.z Then
                    MsgBox("Perfusion Matrix size mismatch!", MsgBoxStyle.Exclamation)
                    NavigateToolStripMenuItem.Checked = False
                    Exit Sub
                End If
            End If
            'otherwise
            Me.IndependentViews = False
        Else
            Me.IndependentViews = True
        End If
    End Sub

    Private Sub LoadFAVolumeAutomaticallyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadFAVolumeAutomaticallyToolStripMenuItem.Click
        If DiffusionVolume IsNot Nothing Then
            LoadFAVolumeAutomaticallyToolStripMenuItem.Checked = Not LoadFAVolumeAutomaticallyToolStripMenuItem.Checked
        Else
            MsgBox("Raw Diffusion Weighted Data not found.")
        End If
    End Sub

#End Region

#Region "Transfer Functions from Min-Max to 0-255 to Min-Max"

    'These two variables are used to scale data back to original values after scaling them from 0-255 so that they can be converted to bitmaps and filters can be applied to them.
    Dim GlobalScaleVariable As Double = 0.0F
    Dim GlobalMinVariable As Double = 0.0F
    Dim CurrentX, CurrentY, CurrentZ As Integer

    Private Sub GenerateConstants(ByVal DataMatrix As Matrix3DSingle)

        CurrentX = DataMatrix.x
        CurrentY = DataMatrix.y
        CurrentZ = DataMatrix.z

        Dim Max As Double = DataMatrix.Maximum
        Dim Min As Double = DataMatrix.Minimum

        GlobalMinVariable = Min
        GlobalScaleVariable = 255 / (Max - Min)

    End Sub
    Private Sub GenerateConstants(ByVal DataMatrix As Matrix3DInt16)

        CurrentX = DataMatrix.x
        CurrentY = DataMatrix.y
        CurrentZ = DataMatrix.z

        Dim Max As Double = DataMatrix.Maximum
        Dim Min As Double = DataMatrix.Minimum

        GlobalMinVariable = Min
        GlobalScaleVariable = 255 / (Max - Min)

    End Sub
    Private Function GetNewUnScaledDataSng(ByVal Matrix As Int16(,,)) As Matrix3DSingle

        'CurrentX CurrentY CurrentZ may change.
        CurrentX = Matrix.GetUpperBound(0)
        CurrentY = Matrix.GetUpperBound(1)
        CurrentZ = Matrix.GetUpperBound(2)

        Dim ReturnVolume As New Matrix3DSingle(CurrentX, CurrentY, CurrentZ)

        Dim i, j, k As Integer
        For i = 0 To CurrentX - 1
            For j = 0 To CurrentY - 1
                For k = 0 To CurrentZ - 1
                    ReturnVolume.data(i, j, k) = CSng(((Matrix(i, j, k) / GlobalScaleVariable) + GlobalMinVariable))
                Next
            Next
        Next

        Return ReturnVolume

    End Function
    Private Function GetNewUnScaledDataInt16(ByVal Matrix As Int16(,,)) As Matrix3DInt16

        'CurrentX CurrentY CurrentZ may change.
        CurrentX = Matrix.GetUpperBound(0)
        CurrentY = Matrix.GetUpperBound(1)
        CurrentZ = Matrix.GetUpperBound(2)

        Dim ReturnVolume As New Matrix3DInt16(CurrentX, CurrentY, CurrentZ)

        Dim i, j, k As Integer
        For i = 0 To CurrentX - 1
            For j = 0 To CurrentY - 1
                For k = 0 To CurrentZ - 1
                    ReturnVolume.data(i, j, k) = CShort(CSng(((Matrix(i, j, k) / GlobalScaleVariable) + GlobalMinVariable)))
                Next
            Next
        Next

        Return ReturnVolume

    End Function

#End Region

#Region "XML Load/Save Serialization Functions"

    Private Sub ToolStripMenuItem5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem5.Click
        If AnatomyVolume IsNot Nothing Then
            Dim temp As New SerializeMatrixtoXML
            temp.SaveAs(AnatomyVolume)
        End If
    End Sub
    Private Sub ToolStripMenuItem6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem6.Click
        If MsgBox("Reduce Significant Figures?", MsgBoxStyle.YesNo, "Save") = MsgBoxResult.Yes Then
            Dim c As Integer
            Try
                Dim test As InputBoxResult = InputBox.Show("Enter number of digits (0-9): ", "Save", "4")
                If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                    c = CInt(test.Text)
                Else
                    Exit Sub
                End If

                For i As Integer = 0 To FAVolume.MatrixD.x - 1
                    For j As Integer = 0 To FAVolume.MatrixD.y - 1
                        For k As Integer = 0 To FAVolume.MatrixD.z - 1
                            FAVolume.MatrixD(i, j, k) = CSng(Math.Round(FAVolume.MatrixD(i, j, k), c))
                        Next
                    Next
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
        If Me.FAVolume IsNot Nothing Then
            Dim temp As New SerializeMatrixtoXML
            temp.SaveAs(FAVolume)
        Else
            MsgBox("Diffusion Volume not loaded or FA Matrix not computed.")
        End If
    End Sub
    Private Sub ToolStripMenuItem7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem7.Click
        If fMRIVolume IsNot Nothing Then
            Dim temp As New SerializeMatrixtoXML
            temp.SaveAs(fMRIVolume)
        End If
    End Sub
    Private Sub ToolStripMenuItem8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem8.Click
        If MsgBox("Reduce Significant Figures?", MsgBoxStyle.YesNo, "Save") = MsgBoxResult.Yes Then
            Try
                Dim c As Integer
                Dim test As InputBoxResult = InputBox.Show("Enter number of digits (0-9): ", "Save", "4")
                If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                    c = CInt(test.Text)
                Else
                    Exit Sub
                End If

                For i As Integer = 0 To PerfusionVolume.MatrixD.x - 1
                    For j As Integer = 0 To PerfusionVolume.MatrixD.y - 1
                        For k As Integer = 0 To PerfusionVolume.MatrixD.z - 1
                            PerfusionVolume.MatrixD(i, j, k) = CSng(Math.Round(PerfusionVolume.MatrixD(i, j, k), c))
                        Next
                    Next
                Next
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
        If PerfusionVolume IsNot Nothing Then
            Dim temp As New SerializeMatrixtoXML
            temp.SaveAs(PerfusionVolume)
        End If
    End Sub
    Private Sub ToolStripMenuItem9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem9.Click
        'anatomy
        Dim temp As New SerializeMatrixtoXML
        AnatomyVolume = New SingleVolume
        AnatomyVolume = temp.LoadFromFile()
        If AnatomyVolume Is Nothing Then Exit Sub
        If AnatomyVolume.Matrix IsNot Nothing Then
            AnatomyDisplay.Text = "Anatomy Data"
            UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
            AddAnatomyHandles()
            AnatomyDisplay.Size = Me.CommonWindowSize
        End If

    End Sub
    Private Sub ToolStripMenuItem10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem10.Click
        'diffusion
        Dim temp As New SerializeMatrixtoXML
        Me.ToolStripButton3.Enabled = True
        FAVolume = New SingleVolume
        FAVolume = temp.LoadFromFile()
        If FAVolume Is Nothing Then Exit Sub
        If FAVolume.MatrixD IsNot Nothing Then
            UpdateDWIVolume(FAVolume, "FA", False, True)
            Me.IsFACalculated = True
            AddDiffusionHandles()
            DiffusionDisplay.Size = Me.CommonWindowSize
        End If
    End Sub
    Private Sub ToolStripMenuItem11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem11.Click
        'fmrmi
        Dim temp As New SerializeMatrixtoXML
        fMRIVolume = New SingleVolume
        Me.ToolStripButton2.Enabled = True
        fMRIVolume = temp.LoadFromFile()
        If fMRIVolume Is Nothing Then Exit Sub
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
        AddfMRIHandles()
        fMRIDisplay.Size = Me.CommonWindowSize
    End Sub
    Private Sub ToolStripMenuItem12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem12.Click
        'perfusion
        Dim temp As New SerializeMatrixtoXML
        PerfusionVolume = New SingleVolume
        PerfusionVolume = temp.LoadFromFile()
        If PerfusionVolume Is Nothing Then Exit Sub
        If PerfusionVolume.MatrixD IsNot Nothing Then
            Me.ToolStripButton1.Enabled = True
            UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
            PerfusionDisplay.Size = Me.CommonWindowSize
            AddPerfusionHandles()
        End If
    End Sub

#End Region

    Private Sub ToolStripMenuItem14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem14.Click
        Dim CompositeFormObject As New CompositeViewerForm
        CompositeFormObject.Show()
        CompositeFormObject.TopMost = True
    End Sub

#Region "Add Handles to Displays"
    Sub AddAnatomyHandles()

        Me.NavigateToolStripMenuItem.Checked = False
        Me.IndependentViews = True

        AddHandler AnatomyDisplay.MouseMovedOnImage, AddressOf MouseMovedOnAnatomy
        AddHandler AnatomyDisplay.CurrentSlice, AddressOf CurrentSliceInformation
        AddHandler AnatomyDisplay.FilteredBaseDataset, AddressOf AnatomyBaseDataFiltered
        AddHandler AnatomyDisplay.SubjectInfo, AddressOf AnatomySubjectInfoShow
        AddHandler AnatomyDisplay.SliceDeleteAfter, AddressOf AnatomySliceDeleteafter
        AddHandler AnatomyDisplay.SliceDeleteThis, AddressOf AnatomySliceDeleteThis
        AddHandler AnatomyDisplay.SliceDeleteBefore, AddressOf AnatomySliceDeleteBefore
    End Sub
    Sub AddfMRIHandles()

        Me.NavigateToolStripMenuItem.Checked = False
        Me.IndependentViews = True

        AddHandler fMRIDisplay.MouseMovedOnImage, AddressOf MouseMovedOnfMRI
        AddHandler fMRIDisplay.CurrentSlice, AddressOf CurrentSliceInformation
        AddHandler fMRIDisplay.FilteredBaseDataset, AddressOf fMRIBaseDataFiltered
        AddHandler fMRIDisplay.SubjectInfo, AddressOf fMRISubjectInfoShow
        AddHandler fMRIDisplay.SliceDeleteAfter, AddressOf fmriSliceDeleteafter
        AddHandler fMRIDisplay.SliceDeleteThis, AddressOf fmriSliceDeleteThis
        AddHandler fMRIDisplay.SliceDeleteBefore, AddressOf fmriSliceDeleteBefore

    End Sub
    Sub AddDiffusionHandles()

        Me.NavigateToolStripMenuItem.Checked = False
        Me.IndependentViews = True

        AddHandler DiffusionDisplay.MouseMovedOnImage, AddressOf MouseMovedOnDiffusion
        AddHandler DiffusionDisplay.CurrentSlice, AddressOf CurrentSliceInformation
        AddHandler DiffusionDisplay.FilteredBaseDataset, AddressOf DiffusionBaseDataFiltered
        AddHandler DiffusionDisplay.SubjectInfo, AddressOf DiffusionSubjectInfoShow
        AddHandler DiffusionDisplay.SliceDeleteAfter, AddressOf diffusionSliceDeleteafter
        AddHandler DiffusionDisplay.SliceDeleteThis, AddressOf diffusionSliceDeleteThis
        AddHandler DiffusionDisplay.SliceDeleteBefore, AddressOf diffusionSliceDeleteBefore
    End Sub
    Sub AddPerfusionHandles()

        Me.NavigateToolStripMenuItem.Checked = False
        Me.IndependentViews = True

        AddHandler PerfusionDisplay.MouseMovedOnImage, AddressOf MouseMovedOnPerfusion
        AddHandler PerfusionDisplay.CurrentSlice, AddressOf CurrentSliceInformation
        AddHandler PerfusionDisplay.FilteredBaseDataset, AddressOf PerfusionBaseDataFiltered
        AddHandler PerfusionDisplay.SubjectInfo, AddressOf PerfusionSubjectInfoShow
        AddHandler PerfusionDisplay.SliceDeleteAfter, AddressOf perfusionSliceDeleteafter
        AddHandler PerfusionDisplay.SliceDeleteThis, AddressOf perfusionSliceDeleteThis
        AddHandler PerfusionDisplay.SliceDeleteBefore, AddressOf perfusionSliceDeleteBefore
    End Sub


#End Region

    Sub AnatomyPLotBackDelegate(ByVal Values As ArrayList)
        Select Case Me.CurrentActiveDisplay
            Case MainForm.DisplayType.Coronal
                Dim map(AnatomyVolume.Matrix.x, AnatomyVolume.Matrix.z) As Short
                For Each i As Integer() In Values
                    map(i(0), i(1)) = 1
                Next
                For x As Integer = 0 To AnatomyVolume.Matrix.x - 1
                    For z As Integer = 0 To AnatomyVolume.Matrix.z - 1
                        AnatomyVolume.Matrix(x, Me.CurrentActiveSlice, z) *= map(x, z)
                    Next
                Next
            Case MainForm.DisplayType.Sagittal
                Dim map(AnatomyVolume.Matrix.y, AnatomyVolume.Matrix.z) As Short
                For Each i As Integer() In Values
                    map(i(0), i(1)) = 1
                Next
                For y As Integer = 0 To AnatomyVolume.Matrix.y - 1
                    For z As Integer = 0 To AnatomyVolume.Matrix.z - 1
                        AnatomyVolume.Matrix(Me.CurrentActiveSlice, y, z) *= map(y, z)
                    Next
                Next
            Case MainForm.DisplayType.Transverse
                Dim map(AnatomyVolume.Matrix.x, AnatomyVolume.Matrix.y) As Short
                For Each i As Integer() In Values
                    map(i(0), i(1)) = 1
                Next
                For x As Integer = 0 To AnatomyVolume.Matrix.x - 1
                    For y As Integer = 0 To AnatomyVolume.Matrix.y - 1
                        AnatomyVolume.Matrix(x, y, Me.CurrentActiveSlice) *= map(x, y)
                    Next
                Next
        End Select
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
    End Sub

#Region "Delete This/Before/After Handlers"

    Private Function DeleteSlices(ByVal data As Object, ByVal dataType As String, ByVal sliceType As String, ByVal sliceNumber As Integer, ByVal cropType As String) As Object
        Dim intMatrix As Matrix3DInt16 = Nothing
        Dim singleMatrix As Matrix3DSingle = Nothing
        Dim isInt As Boolean = True
        If dataType = "int" Then
            isInt = True
            intMatrix = CType(data, Matrix3DInt16)
        ElseIf dataType = "single" Then
            isInt = False
            singleMatrix = CType(data, Matrix3DSingle)
        End If

        Dim truncateChoice As Boolean
        If MessageBox.Show("Do you want to crop the Volume?", "Crop/Zero", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            truncateChoice = True
        Else
            truncateChoice = False
        End If

        Dim resultMatrix As Object = Nothing
        Select Case sliceType
            Case "t" 'new size: z-1 only if truncating
                If isInt Then
                    If truncateChoice Then
                        resultMatrix = New Matrix3DInt16(intMatrix.x, intMatrix.y, intMatrix.z - 1)
                    Else
                        resultMatrix = New Matrix3DInt16(intMatrix.x, intMatrix.y, intMatrix.z)
                    End If
                Else
                    If truncateChoice Then
                        resultMatrix = New Matrix3DSingle(singleMatrix.x, singleMatrix.y, singleMatrix.z - 1)
                    Else
                        resultMatrix = New Matrix3DSingle(singleMatrix.x, singleMatrix.y, singleMatrix.z)
                    End If
                End If
                Dim tempcounter As Integer = 0

                If isInt Then
                    For z As Integer = 0 To CType(resultMatrix, Matrix3DInt16).z - 1
                        Select Case cropType
                            Case "this"
                                If z = sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If z < sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If z > sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, y, tempcounter) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                Else
                    For z As Integer = 0 To CType(resultMatrix, Matrix3DSingle).z - 1
                        Select Case cropType
                            Case "this"
                                If z = sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If z < sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If z > sliceNumber Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, y, tempcounter) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                End If
            Case "s" 'new size: x-1 only if truncating
                If isInt Then
                    If truncateChoice Then
                        resultMatrix = New Matrix3DInt16(intMatrix.x - 1, intMatrix.y, intMatrix.z)
                    Else
                        resultMatrix = New Matrix3DInt16(intMatrix.x, intMatrix.y, intMatrix.z)
                    End If
                Else
                    If truncateChoice Then
                        resultMatrix = New Matrix3DSingle(singleMatrix.x - 1, singleMatrix.y, singleMatrix.z)
                    Else
                        resultMatrix = New Matrix3DSingle(singleMatrix.x, singleMatrix.y, singleMatrix.z)
                    End If
                End If
                Dim tempcounter As Integer = 0

                If isInt Then
                    For x As Integer = 0 To CType(resultMatrix, Matrix3DInt16).x - 1
                        Select Case cropType
                            Case "this"
                                If x = CType(intMatrix, Matrix3DInt16).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For z As Integer = 0 To intMatrix.z - 1
                                                CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For z As Integer = 0 To intMatrix.z - 1
                                            CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If x > CType(intMatrix, Matrix3DInt16).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For z As Integer = 0 To intMatrix.z - 1
                                                CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For z As Integer = 0 To intMatrix.z - 1
                                            CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If x < CType(intMatrix, Matrix3DInt16).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To intMatrix.y - 1
                                            For z As Integer = 0 To intMatrix.z - 1
                                                CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To intMatrix.y - 1
                                        For z As Integer = 0 To intMatrix.z - 1
                                            CType(resultMatrix, Matrix3DInt16).data(tempcounter, y, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                Else
                    For x As Integer = 0 To CType(resultMatrix, Matrix3DSingle).x - 1
                        Select Case cropType
                            Case "this"
                                If x = CType(singleMatrix, Matrix3DSingle).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For z As Integer = 0 To singleMatrix.z - 1
                                                CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If x < CType(singleMatrix, Matrix3DSingle).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For z As Integer = 0 To singleMatrix.z - 1
                                                CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If x > CType(singleMatrix, Matrix3DSingle).x - sliceNumber - 1 Then
                                    If Not truncateChoice Then
                                        For y As Integer = 0 To singleMatrix.y - 1
                                            For z As Integer = 0 To singleMatrix.z - 1
                                                CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For y As Integer = 0 To singleMatrix.y - 1
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            CType(resultMatrix, Matrix3DSingle).data(tempcounter, y, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                End If
            Case "c" 'new size: y-1 only if truncating
                If isInt Then
                    If truncateChoice Then
                        resultMatrix = New Matrix3DInt16(intMatrix.x, intMatrix.y - 1, intMatrix.z)
                    Else
                        resultMatrix = New Matrix3DInt16(intMatrix.x, intMatrix.y, intMatrix.z)
                    End If
                Else
                    If truncateChoice Then
                        resultMatrix = New Matrix3DSingle(singleMatrix.x, singleMatrix.y - 1, singleMatrix.z)
                    Else
                        resultMatrix = New Matrix3DSingle(singleMatrix.x, singleMatrix.y, singleMatrix.z)
                    End If
                End If
                Dim tempcounter As Integer = 0

                If isInt Then
                    For y As Integer = 0 To CType(resultMatrix, Matrix3DInt16).y - 1
                        Select Case cropType
                            Case "this"
                                If y = sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To intMatrix.z - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To intMatrix.z - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If y < sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To intMatrix.z - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To intMatrix.z - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If y > sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To intMatrix.z - 1
                                            For x As Integer = 0 To intMatrix.x - 1
                                                CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To intMatrix.z - 1
                                        For x As Integer = 0 To intMatrix.x - 1
                                            CType(resultMatrix, Matrix3DInt16).data(x, tempcounter, z) = intMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                Else
                    For y As Integer = 0 To CType(resultMatrix, Matrix3DSingle).y - 1
                        Select Case cropType
                            Case "this"
                                If y = sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To singleMatrix.z - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "before"
                                If y < sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To singleMatrix.z - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                            Case "after"
                                If y > sliceNumber Then
                                    If Not truncateChoice Then
                                        For z As Integer = 0 To singleMatrix.z - 1
                                            For x As Integer = 0 To singleMatrix.x - 1
                                                CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = 0
                                            Next
                                        Next
                                        tempcounter += 1
                                    End If
                                Else
                                    For z As Integer = 0 To singleMatrix.z - 1
                                        For x As Integer = 0 To singleMatrix.x - 1
                                            CType(resultMatrix, Matrix3DSingle).data(x, tempcounter, z) = singleMatrix.data(x, y, z)
                                        Next
                                    Next
                                    tempcounter += 1
                                End If
                        End Select
                    Next
                End If
        End Select
        Return resultMatrix
    End Function
    Public Function DeleteSlices(ByVal sender As Object, ByVal data As Object, ByVal dataType As String, ByVal cropType As String) As Object
        Dim SenderString As String = CType(sender, String)
        Dim SenderTypeArg As String = Mid(SenderString, 1, 1)
        Dim SenderNumArg As Integer = CInt(Mid(SenderString, 2, SenderString.Length - 1))
        Return DeleteSlices(data, dataType, Char.ToLower(CChar(SenderTypeArg)).ToString(), SenderNumArg, cropType)
    End Function

    Private Sub AnatomySliceDeleteThis(ByVal sender As Object, ByVal e As EventArgs)
        AnatomyVolume.Matrix = CType(DeleteSlices(sender, AnatomyVolume.Matrix, "int", "this"), Matrix3DInt16)
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
    End Sub
    Private Sub fmriSliceDeleteThis(ByVal sender As Object, ByVal e As EventArgs)
        fMRIVolume.Matrix = CType(DeleteSlices(sender, fMRIVolume.Matrix, "int", "this"), Matrix3DInt16)
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub
    Private Sub diffusionSliceDeleteThis(ByVal sender As Object, ByVal e As EventArgs)
        FAVolume.MatrixD = CType(DeleteSlices(sender, FAVolume.MatrixD, "single", "this"), Matrix3DSingle)
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub
    Private Sub perfusionSliceDeleteThis(ByVal sender As Object, ByVal e As EventArgs)
        PerfusionVolume.MatrixD = CType(DeleteSlices(sender, PerfusionVolume.MatrixD, "single", "this"), Matrix3DSingle)
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub
    Private Sub AnatomySliceDeleteBefore(ByVal sender As Object, ByVal e As EventArgs)
        AnatomyVolume.Matrix = CType(DeleteSlices(sender, AnatomyVolume.Matrix, "int", "before"), Matrix3DInt16)
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
    End Sub
    Private Sub fmriSliceDeleteBefore(ByVal sender As Object, ByVal e As EventArgs)
        fMRIVolume.Matrix = CType(DeleteSlices(sender, fMRIVolume.Matrix, "int", "before"), Matrix3DInt16)
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub
    Private Sub diffusionSliceDeleteBefore(ByVal sender As Object, ByVal e As EventArgs)
        FAVolume.MatrixD = CType(DeleteSlices(sender, FAVolume.MatrixD, "single", "before"), Matrix3DSingle)
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub
    Private Sub perfusionSliceDeleteBefore(ByVal sender As Object, ByVal e As EventArgs)
        PerfusionVolume.MatrixD = CType(DeleteSlices(sender, PerfusionVolume.MatrixD, "single", "before"), Matrix3DSingle)
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub
    Private Sub AnatomySliceDeleteafter(ByVal sender As Object, ByVal e As EventArgs)
        AnatomyVolume.Matrix = CType(DeleteSlices(sender, AnatomyVolume.Matrix, "int", "after"), Matrix3DInt16)
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
    End Sub
    Private Sub fmriSliceDeleteafter(ByVal sender As Object, ByVal e As EventArgs)
        fMRIVolume.Matrix = CType(DeleteSlices(sender, fMRIVolume.Matrix, "int", "after"), Matrix3DInt16)
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub
    Private Sub diffusionSliceDeleteafter(ByVal sender As Object, ByVal e As EventArgs)
        FAVolume.MatrixD = CType(DeleteSlices(sender, FAVolume.MatrixD, "single", "after"), Matrix3DSingle)
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub
    Private Sub perfusionSliceDeleteafter(ByVal sender As Object, ByVal e As EventArgs)
        PerfusionVolume.MatrixD = CType(DeleteSlices(sender, PerfusionVolume.MatrixD, "single", "after"), Matrix3DSingle)
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub
#End Region


    Private Sub ToolStripMenuItem15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem15.Click
        'Create the bitmap and graphics objects.
        Dim b As Bitmap = New Bitmap(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
        Dim g As Graphics = Graphics.FromImage(b)

        Dim s As Size = New Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)

        'Copy the image from the screen. You can customize the size
        'and postions to take the screenshot from.
        Threading.Thread.BeginCriticalRegion()
        g.CopyFromScreen(0, 0, 0, 0, s, CopyPixelOperation.SourceCopy)
        Threading.Thread.EndCriticalRegion()

        Dim saveDlg As SaveFileDialog = New SaveFileDialog
        Dim dlgResult As DialogResult = New DialogResult

        'Set the filter to JPEG files only.
        saveDlg.Filter = "JPEG Files (*.jpg)|*.jpg"
        saveDlg.Title = "Select the file to save the image to.."

        dlgResult = CType(saveDlg.ShowDialog, Windows.Forms.DialogResult)

        If dlgResult = Windows.Forms.DialogResult.OK Then

            'Save the image contained in the picturebox.
            b.Save(saveDlg.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)

        End If

        'Clean up alittle.
        g.Dispose()
        b = Nothing

    End Sub


#Region "File Open Dialogs"
    Private Sub ToolStripMenuItem17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem17.Click
        'anatomy
        If AnatomyVolume IsNot Nothing Then
            AnatomyVolume.MatrixD = Nothing
            Dim SFD As New Windows.Forms.SaveFileDialog
            SFD.AddExtension = False
            SFD.Title = "Save Analyze file as ..."
            SFD.Filter = "All files (*.*)|*.*"
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                HdrImgWriter.WriteToFile(AnatomyVolume, SFD.FileName)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem18.Click
        'fa
        If Me.FAVolume IsNot Nothing Then
            FAVolume.Matrix = Nothing
            Dim SFD As New Windows.Forms.SaveFileDialog
            SFD.AddExtension = False
            SFD.Title = "Save Analyze file as ..."
            SFD.Filter = "All files (*.*)|*.*"
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                HdrImgWriter.WriteToFile(FAVolume, SFD.FileName)
            End If
        Else
            MsgBox("Diffusion Volume not loaded or FA Matrix not computed.")
        End If
    End Sub
    Private Sub ToolStripMenuItem19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem19.Click
        'fmri
        If fMRIVolume IsNot Nothing Then
            fMRIVolume.MatrixD = Nothing
            Dim SFD As New Windows.Forms.SaveFileDialog
            SFD.AddExtension = False
            SFD.Title = "Save Analyze file as ..."
            SFD.Filter = "All files (*.*)|*.*"
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                HdrImgWriter.WriteToFile(fMRIVolume, SFD.FileName, DataType.DT_SIGNED_SHORT)

            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem20.Click
        'perfusion
        If PerfusionVolume IsNot Nothing Then
            PerfusionVolume.Matrix = Nothing
            Dim SFD As New Windows.Forms.SaveFileDialog
            SFD.AddExtension = False
            SFD.Title = "Save Analyze file as ..."
            SFD.Filter = "All files (*.*)|*.*"
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                HdrImgWriter.WriteToFile(PerfusionVolume, SFD.FileName)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem13.Click
        '        LoadSaveMultiDialog.Show()
        CustomFileOpen.Show()
    End Sub
#End Region

    Private Sub MultimodalRegistrationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MultimodalRegistrationToolStripMenuItem.Click

        Dim a As New RegistrationForm(AnatomyVolume.Matrix, FAVolume.MatrixD)
        a.Show()

    End Sub

#Region "ROI CallBack Functions"
    Private Sub ToolStripMenuItem22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem22.Click
        Try
            Dim temp As Short(,) = Nothing
            Select Case AnatomyDisplay.CurrentActiveDisplay
                Case MainForm.DisplayType.Coronal
                    temp = AnatomyVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Sagittal
                    temp = AnatomyVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Transverse
                    temp = AnatomyVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)
            End Select
            Dim tempb As Bitmap = New Bitmap(AnatomyDisplay.CurrentImage(False))
            roiA = New ROIEditor(tempb, temp, 255 / (AnatomyVolume.Matrix.Maximum - AnatomyVolume.Matrix.Minimum), AnatomyVolume.Matrix.Minimum, Mid(GetFirstBit(Me.CurrentActiveDisplay), 1, 1) & CurrentActiveSlice)
            roiA.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow
            roiA.Size = Me.CommonWindowSize
            roiA.Show()

            AddHandler roiA.changeslice, AddressOf ChangeROIsliceA
            AddHandler roiA.PlotBackEvent, AddressOf AnatomyPLotBackDelegate
        Catch ex As Exception
            MessageBox.Show("ROI Editor was not initialized due to internal errors!")
        End Try
    End Sub

    Private Sub ToolStripMenuItem23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem23.Click
        Try
            If FAVolume Is Nothing Then Exit Sub
            If FAVolume.MatrixD Is Nothing Then Exit Sub
            Dim temp As Single(,)
            Select Case DiffusionDisplay.CurrentActiveDisplay
                Case MainForm.DisplayType.Coronal
                    temp = FAVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Sagittal
                    temp = FAVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Transverse
                    temp = FAVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)
                Case Else
                    ReDim temp(AnatomyDisplay.Width, AnatomyDisplay.Height)
            End Select

            Dim tempb As Bitmap = New Bitmap(DiffusionDisplay.CurrentImage(False))
            roiD = New ROIEditor(tempb, temp, 255 / (FAVolume.MatrixD.Maximum - FAVolume.MatrixD.Minimum), FAVolume.MatrixD.Minimum, Mid(GetFirstBit(Me.CurrentActiveDisplay), 1, 1) & CurrentActiveSlice)
            roiD.Show()
            roiD.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow
            roiD.Text = "ROI Window"
            roiD.Size = Me.CommonWindowSize
            'roiD.Location = contentPanel.PointToScreen(DiffusionDisplay.Location)
            'roiD.BringToFront()
            AddHandler roiD.changeslice, AddressOf ChangeROIsliceD
        Catch ex As Exception
            MessageBox.Show("ROI Editor was not initialized due to internal errors!")
        End Try
    End Sub

    Sub ChangeROIsliceA(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim temp As String = CType(sender, String)
            Dim tempm As Short(,) = Nothing
            If temp.Substring(0, 1) = "n" Then
                'next
                If temp.Substring(1, 1) = "t" Then
                    If AnatomyDisplay.CurrentSliceIndex + 1 < AnatomyVolume.Matrix.z Then AnatomyDisplay.ChangeCurrentSliceInfo("t", AnatomyDisplay.CurrentSliceIndex + 1)
                    tempm = AnatomyVolume.Matrix.TransverseSlice(AnatomyDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If AnatomyDisplay.CurrentSliceIndex + 1 < AnatomyVolume.Matrix.y Then AnatomyDisplay.ChangeCurrentSliceInfo("c", AnatomyDisplay.CurrentSliceIndex + 1)
                    tempm = AnatomyVolume.Matrix.CoronalSlice(AnatomyDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If AnatomyDisplay.CurrentSliceIndex + 1 < AnatomyVolume.Matrix.x Then AnatomyDisplay.ChangeCurrentSliceInfo("s", AnatomyDisplay.CurrentSliceIndex + 1)
                    tempm = AnatomyVolume.Matrix.SagittalSlice(AnatomyDisplay.CurrentSliceIndex)
                End If
            ElseIf temp.Substring(0, 1) = "p" Then
                'previous
                If temp.Substring(1, 1) = "t" Then
                    If AnatomyDisplay.CurrentSliceIndex - 1 >= 0 Then AnatomyDisplay.ChangeCurrentSliceInfo("t", AnatomyDisplay.CurrentSliceIndex - 1)
                    tempm = AnatomyVolume.Matrix.TransverseSlice(AnatomyDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If AnatomyDisplay.CurrentSliceIndex - 1 >= 0 Then AnatomyDisplay.ChangeCurrentSliceInfo("c", AnatomyDisplay.CurrentSliceIndex - 1)
                    tempm = AnatomyVolume.Matrix.CoronalSlice(AnatomyDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If AnatomyDisplay.CurrentSliceIndex - 1 >= 0 Then AnatomyDisplay.ChangeCurrentSliceInfo("s", AnatomyDisplay.CurrentSliceIndex - 1)
                    tempm = AnatomyVolume.Matrix.SagittalSlice(AnatomyDisplay.CurrentSliceIndex)
                End If
            End If
            Dim tempb As Bitmap = New Bitmap(AnatomyDisplay.CurrentImage(False))
            roiA.SwitchImage(tempb, tempm, 255 / (AnatomyVolume.Matrix.Maximum - AnatomyVolume.Matrix.Minimum), AnatomyVolume.Matrix.Minimum, temp.Substring(1, 1) & AnatomyDisplay.CurrentSliceIndex)
            roiA.Refresh()
        Catch ex As Exception
            MessageBox.Show("Could not change slice. Please make sure you have not\n scrolled through MetaView window after opening the ROI Editor!")
        End Try
    End Sub
    Sub ChangeROIsliceD(ByVal sender As Object, ByVal e As EventArgs)
        Try

            Dim temp As String = CType(sender, String)
            Dim tempm As Single(,) = Nothing
            If temp.Substring(0, 1) = "n" Then
                'next
                If temp.Substring(1, 1) = "t" Then
                    If DiffusionDisplay.CurrentSliceIndex + 1 < FAVolume.MatrixD.z Then DiffusionDisplay.ChangeCurrentSliceInfo("t", DiffusionDisplay.CurrentSliceIndex + 1)
                    tempm = FAVolume.MatrixD.TransverseSlice(DiffusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If DiffusionDisplay.CurrentSliceIndex + 1 < FAVolume.MatrixD.y Then DiffusionDisplay.ChangeCurrentSliceInfo("c", DiffusionDisplay.CurrentSliceIndex + 1)
                    tempm = FAVolume.MatrixD.CoronalSlice(DiffusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If DiffusionDisplay.CurrentSliceIndex + 1 < FAVolume.MatrixD.x Then DiffusionDisplay.ChangeCurrentSliceInfo("s", DiffusionDisplay.CurrentSliceIndex + 1)
                    tempm = FAVolume.MatrixD.SagittalSlice(DiffusionDisplay.CurrentSliceIndex)
                End If
            ElseIf temp.Substring(0, 1) = "p" Then
                'previous
                If temp.Substring(1, 1) = "t" Then
                    If DiffusionDisplay.CurrentSliceIndex - 1 >= 0 Then DiffusionDisplay.ChangeCurrentSliceInfo("t", DiffusionDisplay.CurrentSliceIndex - 1)
                    tempm = FAVolume.MatrixD.TransverseSlice(DiffusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If DiffusionDisplay.CurrentSliceIndex - 1 >= 0 Then DiffusionDisplay.ChangeCurrentSliceInfo("c", DiffusionDisplay.CurrentSliceIndex - 1)
                    tempm = FAVolume.MatrixD.CoronalSlice(DiffusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If DiffusionDisplay.CurrentSliceIndex - 1 >= 0 Then DiffusionDisplay.ChangeCurrentSliceInfo("s", DiffusionDisplay.CurrentSliceIndex - 1)
                    tempm = FAVolume.MatrixD.SagittalSlice(DiffusionDisplay.CurrentSliceIndex)
                End If
            End If

            Dim tempb As Bitmap = New Bitmap(DiffusionDisplay.CurrentImage(False))

            roiD.SwitchImage(tempb, tempm, 255 / (FAVolume.MatrixD.Maximum - FAVolume.MatrixD.Minimum), FAVolume.MatrixD.Minimum, temp.Substring(1, 1) & DiffusionDisplay.CurrentSliceIndex)
            roiD.Refresh()
        Catch ex As Exception
            MessageBox.Show("Could not change slice. Please make sure you have not\n scrolled through MetaView window after opening the ROI Editor!")
            MessageBox.Show(ex.Message)

        End Try

    End Sub
    Sub ChangeROIsliceF(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim temp As String = CType(sender, String)
            Dim tempm As Short(,) = Nothing
            If temp.Substring(0, 1) = "n" Then
                'next
                If temp.Substring(1, 1) = "t" Then
                    If fMRIDisplay.CurrentSliceIndex + 1 < fMRIVolume.Matrix.z Then fMRIDisplay.ChangeCurrentSliceInfo("t", fMRIDisplay.CurrentSliceIndex + 1)
                    tempm = fMRIVolume.Matrix.TransverseSlice(fMRIDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If fMRIDisplay.CurrentSliceIndex + 1 < fMRIVolume.Matrix.y Then fMRIDisplay.ChangeCurrentSliceInfo("c", fMRIDisplay.CurrentSliceIndex + 1)
                    tempm = fMRIVolume.Matrix.CoronalSlice(fMRIDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If fMRIDisplay.CurrentSliceIndex + 1 < fMRIVolume.Matrix.x Then fMRIDisplay.ChangeCurrentSliceInfo("s", fMRIDisplay.CurrentSliceIndex + 1)
                    tempm = fMRIVolume.Matrix.SagittalSlice(fMRIDisplay.CurrentSliceIndex)
                End If
            ElseIf temp.Substring(0, 1) = "p" Then
                'previous
                If temp.Substring(1, 1) = "t" Then
                    If fMRIDisplay.CurrentSliceIndex - 1 >= 0 Then fMRIDisplay.ChangeCurrentSliceInfo("t", fMRIDisplay.CurrentSliceIndex - 1)
                    tempm = fMRIVolume.Matrix.TransverseSlice(fMRIDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If fMRIDisplay.CurrentSliceIndex - 1 >= 0 Then fMRIDisplay.ChangeCurrentSliceInfo("c", fMRIDisplay.CurrentSliceIndex - 1)
                    tempm = fMRIVolume.Matrix.CoronalSlice(fMRIDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If fMRIDisplay.CurrentSliceIndex - 1 >= 0 Then fMRIDisplay.ChangeCurrentSliceInfo("s", fMRIDisplay.CurrentSliceIndex - 1)
                    tempm = fMRIVolume.Matrix.SagittalSlice(fMRIDisplay.CurrentSliceIndex)
                End If
            End If

            roiF.SwitchImage(fMRIDisplay.CurrentImage(False), tempm, 255 / (fMRIVolume.Matrix.Maximum - fMRIVolume.Matrix.Minimum), fMRIVolume.Matrix.Minimum, temp.Substring(1, 1) & fMRIDisplay.CurrentSliceIndex)
            roiF.Refresh()
        Catch ex As Exception
            MessageBox.Show("Could not change slice. Please make sure you have not\n scrolled through MetaView window after opening the ROI Editor!")
            MessageBox.Show(ex.Message)
        End Try

    End Sub
    Sub ChangeROIsliceP(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim temp As String = CType(sender, String)
            Dim tempm As Single(,) = Nothing
            If temp.Substring(0, 1) = "n" Then
                'next
                If temp.Substring(1, 1) = "t" Then
                    If PerfusionDisplay.CurrentSliceIndex + 1 < PerfusionVolume.MatrixD.z Then PerfusionDisplay.ChangeCurrentSliceInfo("t", PerfusionDisplay.CurrentSliceIndex + 1)
                    tempm = PerfusionVolume.MatrixD.TransverseSlice(PerfusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If PerfusionDisplay.CurrentSliceIndex + 1 < PerfusionVolume.MatrixD.y Then PerfusionDisplay.ChangeCurrentSliceInfo("c", PerfusionDisplay.CurrentSliceIndex + 1)
                    tempm = PerfusionVolume.MatrixD.CoronalSlice(PerfusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If PerfusionDisplay.CurrentSliceIndex + 1 < PerfusionVolume.MatrixD.x Then PerfusionDisplay.ChangeCurrentSliceInfo("s", PerfusionDisplay.CurrentSliceIndex + 1)
                    tempm = PerfusionVolume.MatrixD.SagittalSlice(PerfusionDisplay.CurrentSliceIndex)
                End If
            ElseIf temp.Substring(0, 1) = "p" Then
                'previous
                If temp.Substring(1, 1) = "t" Then
                    If PerfusionDisplay.CurrentSliceIndex - 1 >= 0 Then PerfusionDisplay.ChangeCurrentSliceInfo("t", PerfusionDisplay.CurrentSliceIndex - 1)
                    tempm = PerfusionVolume.MatrixD.TransverseSlice(PerfusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "c" Then
                    If PerfusionDisplay.CurrentSliceIndex - 1 >= 0 Then PerfusionDisplay.ChangeCurrentSliceInfo("c", PerfusionDisplay.CurrentSliceIndex - 1)
                    tempm = PerfusionVolume.MatrixD.CoronalSlice(PerfusionDisplay.CurrentSliceIndex)
                ElseIf temp.Substring(1, 1) = "s" Then
                    If PerfusionDisplay.CurrentSliceIndex - 1 >= 0 Then PerfusionDisplay.ChangeCurrentSliceInfo("s", PerfusionDisplay.CurrentSliceIndex - 1)
                    tempm = PerfusionVolume.MatrixD.SagittalSlice(PerfusionDisplay.CurrentSliceIndex)
                End If
            End If
            roiP.SwitchImage(PerfusionDisplay.CurrentImage(False), tempm, 255 / (PerfusionVolume.MatrixD.Maximum - PerfusionVolume.MatrixD.Minimum), PerfusionVolume.MatrixD.Minimum, temp.Substring(1, 1) & PerfusionDisplay.CurrentSliceIndex)
            roiP.Refresh()
        Catch ex As Exception
            MessageBox.Show("Could not change slice. Please make sure you have not\n scrolled through MetaView window after opening the ROI Editor!")
        End Try

    End Sub

    Private Sub ToolStripMenuItem24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem24.Click
        Try
            Dim temp As Short(,) = Nothing
            Select Case fMRIDisplay.CurrentActiveDisplay
                Case MainForm.DisplayType.Coronal
                    temp = fMRIVolume.Matrix.CoronalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Sagittal
                    temp = fMRIVolume.Matrix.SagittalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Transverse
                    temp = fMRIVolume.Matrix.TransverseSlice(Me.CurrentActiveSlice)
                Case Else
                    ReDim temp(fMRIDisplay.Width, fMRIDisplay.Height)
            End Select
            roiF = New ROIEditor(fMRIDisplay.CurrentImage(False), temp, 255 / (fMRIVolume.Matrix.Maximum - fMRIVolume.Matrix.Minimum), fMRIVolume.Matrix.Minimum, Mid(GetFirstBit(Me.CurrentActiveDisplay), 1, 1) & CurrentActiveSlice)
            roiF.Show()
            roiF.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow
            roiF.Text = "ROI Window"
            roiF.Size = Me.CommonWindowSize
            'roiF.Location = contentPanel.PointToScreen(fMRIDisplay.Location)
            'roiF.BringToFront()
            AddHandler roiF.changeslice, AddressOf ChangeROIsliceF
        Catch ex As Exception
            MessageBox.Show("ROI Editor was not initialized due to internal errors!")
        End Try

    End Sub

    Private Sub ToolStripMenuItem25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem25.Click
        Try

            Dim temp As Single(,) = Nothing
            Select Case PerfusionDisplay.CurrentActiveDisplay
                Case MainForm.DisplayType.Coronal
                    temp = PerfusionVolume.MatrixD.CoronalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Sagittal
                    temp = PerfusionVolume.MatrixD.SagittalSlice(Me.CurrentActiveSlice)
                Case MainForm.DisplayType.Transverse
                    temp = PerfusionVolume.MatrixD.TransverseSlice(Me.CurrentActiveSlice)
                Case Else
                    ReDim temp(PerfusionDisplay.Width, PerfusionDisplay.Height)
            End Select

            roiP = New ROIEditor(PerfusionDisplay.CurrentImage(False), temp, 255 / (PerfusionVolume.MatrixD.Maximum - PerfusionVolume.MatrixD.Minimum), PerfusionVolume.MatrixD.Minimum, Mid(GetFirstBit(Me.CurrentActiveDisplay), 1, 1) & CurrentActiveSlice)
            roiP.Show()
            roiP.FormBorderStyle = Windows.Forms.FormBorderStyle.SizableToolWindow
            roiP.Text = "ROI Window"
            roiP.Size = Me.CommonWindowSize
            'roiP.Location = contentPanel.PointToScreen(PerfusionDisplay.Location)
            'roiP.BringToFront()
            AddHandler roiP.changeslice, AddressOf ChangeROIsliceP
        Catch ex As Exception
            MessageBox.Show("ROI Editor was not initialized due to internal errors!")
        End Try

    End Sub
#End Region

#Region "Refresh Display Functions"
    Private Sub PerfusionRefreshDisplayToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshDisplayToolStripMenuItem1.Click
        Me.ToolStripButton1.Enabled = True
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
        PerfusionDisplay.Size = Me.CommonWindowSize
        AddPerfusionHandles()
    End Sub

    Private Sub RefreshDisplayToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshDisplayToolStripMenuItem2.Click
        Me.ToolStripButton1.Enabled = True
        UpdatefMRIVolume(fMRIVolume, "fmri", True, False)
        fMRIDisplay.Size = Me.CommonWindowSize
        AddfMRIHandles()
    End Sub

    Private Sub RefreshDisplayToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshDisplayToolStripMenuItem.Click
        Me.ToolStripButton1.Enabled = True
        UpdateDWIVolume(FAVolume, "FA", False, True)
        DiffusionDisplay.Size = Me.CommonWindowSize
        AddDiffusionHandles()
    End Sub

    Private Sub RefreshDisplayToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshDisplayToolStripMenuItem3.Click
        Me.ToolStripButton1.Enabled = True
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
        AnatomyDisplay.Size = Me.CommonWindowSize
        AddAnatomyHandles()
    End Sub
#End Region

#Region "Manual Resize Rotate Functions"
    Private Sub ManualResizeRotateAnatomyDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualResizeRotateAnatomyDataToolStripMenuItem.Click
        Dim test As InputBoxResult = InputBox.Show("Enter Rotation (along x,y,z axis in degrees) & Translation Parameters (along x,y,z axis in datapoints)" & vbNewLine & "(angles: yz,xz,xy distances: x,y,z)", "Parameters", Me.AnatomyVolume.OffCenterAngle.x & "," & Me.AnatomyVolume.OffCenterAngle.y & "," & Me.AnatomyVolume.OffCenterAngle.z & "," & Me.AnatomyVolume.Center.x & "," & Me.AnatomyVolume.Center.y & "," & Me.AnatomyVolume.Center.z)
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        AnatomyVolume.Matrix.RotateAndTranslate(CSng(temp(0)), CSng(temp(1)), CSng(temp(2)), CSng(temp(3)), CSng(temp(4)), CSng(temp(5)))
        UpdateAnatomyVolume(AnatomyVolume, "Anatomy", True, False)
    End Sub

    Private Sub ManualResizeRotateDiffusionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualResizeRotateDiffusionToolStripMenuItem.Click
        Dim test As InputBoxResult = InputBox.Show("Enter Rotation & Translation Parameters" & vbNewLine & "(angles: yz,xz,xy distances: x,y,z)", "Parameters", "0,0,0,0,0,0")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        FAVolume.Matrix.RotateAndTranslate(CSng(temp(0)), CSng(temp(1)), CSng(temp(2)), CSng(temp(3)), CSng(temp(4)), CSng(temp(5)))

        UpdateDWIVolume(FAVolume, "Diffusion", True, False)
    End Sub

    Private Sub ManualResizeRotateFAToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualResizeRotateFAToolStripMenuItem.Click
        Dim test As InputBoxResult = InputBox.Show("Enter Rotation & Translation Parameters" & vbNewLine & "(angles: yz,xz,xy distances: x,y,z)", "Parameters", "0,0,0,0,0,0")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        FAVolume.MatrixD.RotateAndTranslate(CSng(temp(0)), CSng(temp(1)), CSng(temp(2)), CSng(temp(3)), CSng(temp(4)), CSng(temp(5)))

        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ManualResizeRotateFMRIDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualResizeRotateFMRIDataToolStripMenuItem.Click
        Dim test As InputBoxResult = InputBox.Show("Enter Rotation & Translation Parameters" & vbNewLine & "(angles: yz,xz,xy distances: x,y,z)", "Parameters", "0,0,0,0,0,0")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        fMRIVolume.Matrix.RotateAndTranslate(CSng(temp(0)), CSng(temp(1)), CSng(temp(2)), CSng(temp(3)), CSng(temp(4)), CSng(temp(5)))

        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ManualResizeRotatePerfusionRatioDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualResizeRotatePerfusionRatioDataToolStripMenuItem.Click
        Dim test As InputBoxResult = InputBox.Show("Enter Rotation & Translation Parameters" & vbNewLine & "(angles: yz,xz,xy distances: x,y,z)", "Parameters", "0,0,0,0,0,0")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        PerfusionVolume.MatrixD.RotateAndTranslate(CSng(temp(0)), CSng(temp(1)), CSng(temp(2)), CSng(temp(3)), CSng(temp(4)), CSng(temp(5)))
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub
#End Region

    Private Sub LoadRawDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadRawDataToolStripMenuItem.Click
        UpdatePerfusionVolume(PerfusionVolume, "RAW Perfusion", True, False)
    End Sub

    Private Sub LoadPerfusionRatioDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadPerfusionRatioDataToolStripMenuItem.Click
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion Ratios", False, True)
    End Sub

#Region "DTI Functions"
    Private Sub LoadDiffusionDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadDiffusionDataToolStripMenuItem.Click
        UpdateDWIVolume(FAVolume, "Diffusion", True, False)
    End Sub
    Private Sub LoadFADataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadFADataToolStripMenuItem.Click
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub
    Private Sub ToolStripMenuItem26_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem26.Click
        If DiffusionDisplay IsNot Nothing And DiffusionVolume IsNot Nothing Then
            DTIClass = New frmDTIParamertersSet(DiffusionVolume.Matrix, DiffusionVolume.Matrix.i, DiffusionVolume.Matrix.j, DiffusionVolume.Matrix.k)
            DTIClass.Show()
            DTIClass.Visible = True
            AddHandler DTIClass.FACalculationComplete, AddressOf Me.SwitchToFA

        End If
    End Sub
    Private Sub ToolStripMenuItem27_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem27.Click
        'trace map
        If DTIClass IsNot Nothing Then
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnAD
            UpdateDWIVolume(tempvolume, "Trace", False, True)
            If MsgBox("Save as XML? ", MsgBoxStyle.YesNo, "Export") = MsgBoxResult.Yes Then
                Dim tempsaver As New SerializeMatrixtoXML
                tempsaver.SaveAs(tempvolume)
            Else
                Dim sfd As New SaveFileDialog
                sfd.Filter = "Analyze (*.hdr)|*.hdr"
                sfd.Title = "Save As.."
                If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                    HdrImgWriter.WriteToFile(tempvolume, sfd.FileName)
                End If
            End If
        End If
    End Sub
    Private Sub PrincipleEigenvalueMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrincipleEigenvalueMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            UpdateDWIVolume(New SingleVolume(DTIClass.ReturnEigenValue(ComputeDTI.Order.Big), FAVolume), "Principal Eigenvalue Map", True, True)
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Big)
            If MsgBox("Save as XML? ", MsgBoxStyle.YesNo, "Export") = MsgBoxResult.Yes Then
                Dim tempsaver As New SerializeMatrixtoXML
                tempsaver.SaveAs(tempvolume)
            Else
                Dim sfd As New SaveFileDialog
                sfd.Filter = "Analyze (*.hdr)|*.hdr"
                sfd.Title = "Save As.."
                If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                    HdrImgWriter.WriteToFile(tempvolume, sfd.FileName)
                End If
            End If
        End If
    End Sub
    Private Sub SecondaryEigenvalueMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SecondaryEigenvalueMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            UpdateDWIVolume(New SingleVolume(DTIClass.ReturnEigenValue(ComputeDTI.Order.Medium), FAVolume), "Secondary Eigenvalue Map", False, True)
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Medium)
            If MsgBox("Save as XML? ", MsgBoxStyle.YesNo, "Export") = MsgBoxResult.Yes Then
                Dim tempsaver As New SerializeMatrixtoXML
                tempsaver.SaveAs(tempvolume)
            Else
                Dim sfd As New SaveFileDialog
                sfd.Filter = "Analyze (*.hdr)|*.hdr"
                sfd.Title = "Save As.."
                If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                    HdrImgWriter.WriteToFile(tempvolume, sfd.FileName)
                End If
            End If
        End If

    End Sub
    Private Sub TertiaryEigenvalueMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TertiaryEigenvalueMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Small)
            UpdateDWIVolume(tempvolume, "Tertiary Eigenvalue Map", False, True)
            If MsgBox("Save as XML? ", MsgBoxStyle.YesNo, "Export") = MsgBoxResult.Yes Then
                Dim tempsaver As New SerializeMatrixtoXML
                tempsaver.SaveAs(tempvolume)
            Else
                Dim sfd As New SaveFileDialog
                sfd.Filter = "Analyze (*.hdr)|*.hdr"
                sfd.Title = "Save As.."
                If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                    HdrImgWriter.WriteToFile(tempvolume, sfd.FileName)
                End If
            End If
        End If
    End Sub
    Private Sub ThresholdMaskFaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThresholdMaskFaToolStripMenuItem.Click
        If Me.IsFACalculated = True Then
            Dim reversible As Boolean
            If MsgBox("Do you want this filter to be reversible?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                reversible = True
            Else
                reversible = False
            End If

            Dim test As InputBoxResult = InputBox.Show("Enter Thresholds (min,max) : ", "Thresholds", "0.2,0.9")
            Dim temp2() As String
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp2 = test.Text.Split(CChar(","))
            Else
                Exit Sub
            End If

            If reversible Then
                Dim temp As Matrix3DSingle = New Matrix3DSingle(FAVolume.MatrixD.data, FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)
                UpdateDWIVolume(New SingleVolume(temp.Threshold(CSng(temp2(0)), CSng(temp2(1))), FAVolume), "Temporary Thresholded FA", False, True)
            Else
                UpdateDWIVolume(New SingleVolume(FAVolume.MatrixD.Threshold(CSng(temp2(0)), CSng(temp2(1))), FAVolume), "Thresholded FA", False, True)
            End If
        Else
            MsgBox("Please compute FA values first!")
        End If

    End Sub
    Private Sub IntensityMaskFAToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IntensityMaskFAToolStripMenuItem.Click
        If Me.IsFACalculated = True Then
            Dim reversible As Boolean
            If MsgBox("Do you want this filter to be reversible?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                reversible = True
            Else
                reversible = False
            End If

            Dim test As InputBoxResult = InputBox.Show("Enter Thresholds (min,max) : ", "Thresholds", "0,0")
            Dim temp2() As String
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp2 = test.Text.Split(CChar(","))
            Else
                Exit Sub
            End If
            Dim temp As New Matrix3DSingle(FAVolume.MatrixD.x, FAVolume.Matrix.y, FAVolume.Matrix.z)
            For i As Integer = 0 To FAVolume.MatrixD.x - 1
                For j As Integer = 0 To FAVolume.MatrixD.y - 1
                    For k As Integer = 0 To FAVolume.MatrixD.z - 1
                        If FAVolume.Matrix(i, j, k) < CSng(temp2(0)) Or FAVolume.Matrix(i, j, k) > CSng(temp2(1)) Then
                            If Not reversible Then FAVolume.MatrixD(i, j, k) = 0
                            If reversible Then temp(i, j, k) = 0
                        Else
                            If reversible Then temp(i, j, k) = FAVolume.MatrixD(i, j, k)
                        End If
                    Next
                Next
            Next

            If reversible Then
                UpdateDWIVolume(New SingleVolume(temp, FAVolume), "Temporary Masked FA", False, True)
            Else
                UpdateDWIVolume(FAVolume, "Masked FA", False, True)
            End If
        Else
            MsgBox("Please compute FA values first!")
        End If
    End Sub
    Private Sub ToolStripMenuItem60_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem60.Click
        Dim resizer As New MatrixResizer.MatrixResize
        FAVolume.MatrixD = resizer.Resize(FAVolume.MatrixD, FAVolume.FOV.x, FAVolume.FOV.y, FAVolume.FOV.z)
        UpdateDWIVolume(FAVolume, "Resized FA", False, True)
        If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < FAVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < FAVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < FAVolume.MatrixD.y) Then
                DiffusionDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem61_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem68.Click
        Dim resizer As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation
        FAVolume.MatrixD = resizer.ResizeVolumes(FAVolume.MatrixD, FAVolume.Center, AnatomyVolume.Center, FAVolume.FOV, AnatomyVolume.FOV)
        UpdateDWIVolume(FAVolume, "Matched FA", False, True)
        If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < FAVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < FAVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < FAVolume.MatrixD.y) Then
                DiffusionDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem62_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem62.Click
        GenerateConstants(FAVolume.MatrixD)
        DiffusionDisplay.OpenFile(FAVolume.MatrixD, "FA", CSng(1 / GlobalScaleVariable), CSng(GlobalMinVariable))
        If DiffusionDisplay IsNot Nothing And FAVolume IsNot Nothing Then
            If (Me.CurrentActiveDisplay = MainForm.DisplayType.Transverse And Me.CurrentActiveSlice < FAVolume.MatrixD.z) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Sagittal And Me.CurrentActiveSlice < FAVolume.MatrixD.x) Or (Me.CurrentActiveDisplay = MainForm.DisplayType.Coronal And Me.CurrentActiveSlice < FAVolume.MatrixD.y) Then
                DiffusionDisplay.ChangeCurrentSliceInfo(Mid(Me.GetFirstBit(Me.CurrentActiveDisplay), 1, 1), CurrentActiveSlice)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem89_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem89.Click
        If FAVolume IsNot Nothing Then
            Dim DTIDirectionMapViewer As New FAMorphCorrection
            DTIDirectionMapViewer.Show()
            DTIDirectionMapViewer.Text = "FA Noise Removal"
            DTIDirectionMapViewer.ShowInTaskbar = True
        End If
    End Sub
    Private Sub ToolStripMenuItem90_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem90.Click
        MessageBox.Show("Please use the command line utility CoregisterDTI.exe")
    End Sub
    Private Sub ToolStripMenuItem91_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem91.Click
        For i As Integer = 0 To DiffusionVolume.Matrix.l - 1
            UpdateDWIVolume(New SingleVolume(New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(i)), DiffusionVolume.FOV, DiffusionVolume.Center), "Direction " & i, True, False)
        Next
    End Sub
    Private Sub PrimaryEigenvectorMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrimaryEigenvectorMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then

            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Big)
            UpdateDWIVolume(tempvolume, "Principal Eigenvector Map", False, True)
            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempvolume)

        End If
    End Sub
    Private Sub SecondaryEigenvectorMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SecondaryEigenvectorMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Medium)
            UpdateDWIVolume(tempvolume, "Secondary Eigenvector Map", False, True)

            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempvolume)
        End If
    End Sub
    Private Sub TertiaryEigenvectorMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TertiaryEigenvectorMapToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Small)
            UpdateDWIVolume(tempvolume, "Tertiary Eigenvector Map", False, True)

            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempvolume)
        End If
    End Sub
    Private Sub ToolStripMenuItem85_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem85.Click
        If DTIClass IsNot Nothing Then

            Dim tempvolume As New SingleVolume
            tempvolume.FOV = FAVolume.FOV
            tempvolume.Center = FAVolume.Center
            tempvolume.HeaderFileName = FAVolume.HeaderFileName
            tempvolume.MatrixD = DTIClass.ReturnLinearlization
            UpdateDWIVolume(tempvolume, "Linearization", False, True)

            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempvolume)
        End If

    End Sub
    Private Sub PrimaryEigenvectorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrimaryEigenvectorToolStripMenuItem.Click
        'rpimary
        If DTIClass IsNot Nothing Then
            Dim temp2 As Matrix4DdoubleS = DTIClass.ReturnEigenVector(ComputeDTI.Order.Big)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        temp2.data(i, j, k, 0) = Math.Abs(temp2.data(i, j, k, 0) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 1) = Math.Abs(temp2.data(i, j, k, 1) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 2) = Math.Abs(temp2.data(i, j, k, 2) * DTIClass.ReturnFA.data(i, j, k))
                    Next
                Next
            Next

            Dim max As Double = temp2.data(0, 0, 0, 0)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        For l As Integer = 0 To temp2.l - 1
                            If temp2.data(i, j, k, l) > max Then max = temp2.data(i, j, k, l)
                        Next
                    Next
                Next
            Next
            Dim ColorMatrix As New MatrixDataStructures.ColorMatrix(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)
            For i As Integer = 0 To FAVolume.MatrixD.x - 1
                For j As Integer = 0 To FAVolume.MatrixD.y - 1
                    For k As Integer = 0 To FAVolume.MatrixD.z - 1
                        ColorMatrix.data(i, j, k) = Color.FromArgb(CInt(255 * (temp2.data(i, j, k, 0) / max)), CInt(255 * (temp2.data(i, j, k, 1) / max)), CInt(255 * (temp2.data(i, j, k, 2) / max)))
                    Next
                Next
            Next
            '            CompositeDisplay.Show()
            ' CompositeDisplay.MdiParent = Me
            '           If CompositeDisplay.Visible = False Then CompositeDisplay.Visible = True
            DiffusionDisplay.OpenFile(ColorMatrix, "Primary Eigenvector")

        Else
            MsgBox("RAW DTI Eigenvector & Eigenvalue classes are not loaded. Please re-compute DTI", MsgBoxStyle.OkOnly, "MetaView")
        End If
    End Sub
    Private Sub SecondaryEigenvectorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SecondaryEigenvectorToolStripMenuItem.Click
        'secondary colormap
        If DTIClass IsNot Nothing Then
            Dim temp2 As Matrix4DdoubleS = DTIClass.ReturnEigenVector(ComputeDTI.Order.Medium)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        temp2.data(i, j, k, 0) = Math.Abs(temp2.data(i, j, k, 0) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 1) = Math.Abs(temp2.data(i, j, k, 1) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 2) = Math.Abs(temp2.data(i, j, k, 2) * DTIClass.ReturnFA.data(i, j, k))
                    Next
                Next
            Next
            Dim max As Double = temp2.data(0, 0, 0, 0)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        For l As Integer = 0 To temp2.l - 1
                            If temp2.data(i, j, k, l) > max Then max = temp2.data(i, j, k, l)
                        Next
                    Next
                Next
            Next
            Dim ColorMatrix As New MatrixDataStructures.ColorMatrix(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)
            For i As Integer = 0 To FAVolume.MatrixD.x - 1
                For j As Integer = 0 To FAVolume.MatrixD.y - 1
                    For k As Integer = 0 To FAVolume.MatrixD.z - 1
                        ColorMatrix.data(i, j, k) = Color.FromArgb(CInt(255 * (temp2.data(i, j, k, 0) / max)), CInt(255 * (temp2.data(i, j, k, 1) / max)), CInt(255 * (temp2.data(i, j, k, 2) / max)))
                    Next
                Next
            Next
            DiffusionDisplay.OpenFile(ColorMatrix, "Secondary Eigenvector")

        Else
            MsgBox("RAW DTI Eigenvector & Eigenvalue classes are not loaded. Please re-compute DTI", MsgBoxStyle.OkOnly, "MetaView")
        End If
    End Sub
    Private Sub TertiaryEigenvectorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TertiaryEigenvectorToolStripMenuItem.Click
        If DTIClass IsNot Nothing Then
            Dim temp2 As Matrix4DdoubleS = DTIClass.ReturnEigenVector(ComputeDTI.Order.Small)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        temp2.data(i, j, k, 0) = Math.Abs(temp2.data(i, j, k, 0) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 1) = Math.Abs(temp2.data(i, j, k, 1) * DTIClass.ReturnFA.data(i, j, k))
                        temp2.data(i, j, k, 2) = Math.Abs(temp2.data(i, j, k, 2) * DTIClass.ReturnFA.data(i, j, k))
                    Next
                Next
            Next
            Dim max As Double = temp2.data(0, 0, 0, 0)
            For i As Integer = 0 To temp2.i - 1
                For j As Integer = 0 To temp2.j - 1
                    For k As Integer = 0 To temp2.k - 1
                        For l As Integer = 0 To temp2.l - 1
                            If temp2.data(i, j, k, l) > max Then max = temp2.data(i, j, k, l)
                        Next
                    Next
                Next
            Next
            Dim ColorMatrix As New MatrixDataStructures.ColorMatrix(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)
            For i As Integer = 0 To FAVolume.MatrixD.x - 1
                For j As Integer = 0 To FAVolume.MatrixD.y - 1
                    For k As Integer = 0 To FAVolume.MatrixD.z - 1
                        ColorMatrix.data(i, j, k) = Color.FromArgb(CInt(255 * (temp2.data(i, j, k, 0) / max)), CInt(255 * (temp2.data(i, j, k, 1) / max)), CInt(255 * (temp2.data(i, j, k, 2) / max)))
                    Next
                Next
            Next
            DiffusionDisplay.OpenFile(ColorMatrix, "Tertiary Eigenvector")

        Else
            MsgBox("RAW DTI Eigenvector & Eigenvalue classes are not loaded. Please re-compute DTI", MsgBoxStyle.OkOnly, "MetaView")
        End If
    End Sub
#End Region


#Region "Insert zero slice subs"
    Private Sub AtBeginToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtBeginToolStripMenuItem.Click
        'transverset at begin insert at anatomy
        AnatomyVolume.Matrix.InsertSlice(0, "T")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub AtEndToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtEndToolStripMenuItem.Click
        'transverse at end of anatomy
        AnatomyVolume.Matrix.InsertSlice(1, "T")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub AtBeginToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtBeginToolStripMenuItem1.Click
        'coronal at begin of anatomy
        AnatomyVolume.Matrix.InsertSlice(0, "C")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub AtEndToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtEndToolStripMenuItem1.Click
        'coronal at end of anatomy
        AnatomyVolume.Matrix.InsertSlice(1, "C")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub AtBeginToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtBeginToolStripMenuItem2.Click
        'sagital at beginning of anatomy
        AnatomyVolume.Matrix.InsertSlice(1, "S")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub AtEndToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtEndToolStripMenuItem2.Click
        'sagital at end of anatomy
        AnatomyVolume.Matrix.InsertSlice(1, "S")
        UpdateAnatomyVolume(AnatomyVolume, "New Anatomy", True, False)
    End Sub

    Private Sub ToolStripMenuItem31_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem31.Click
        FAVolume.MatrixD.InsertSlice(0, "T")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem32_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem32.Click
        FAVolume.MatrixD.InsertSlice(1, "T")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem34_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem34.Click
        FAVolume.MatrixD.InsertSlice(0, "C")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem35_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem35.Click
        FAVolume.MatrixD.InsertSlice(1, "C")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem37_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem37.Click
        FAVolume.MatrixD.InsertSlice(0, "S")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem38_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem38.Click
        FAVolume.MatrixD.InsertSlice(0, "S")
        UpdateDWIVolume(FAVolume, "FA", False, True)
    End Sub

    Private Sub ToolStripMenuItem41_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem41.Click
        fMRIVolume.Matrix.InsertSlice(0, "T")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem42_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem42.Click
        fMRIVolume.Matrix.InsertSlice(1, "T")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem44_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem44.Click
        fMRIVolume.Matrix.InsertSlice(0, "C")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem45_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem45.Click
        fMRIVolume.Matrix.InsertSlice(1, "C")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem47_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem47.Click
        fMRIVolume.Matrix.InsertSlice(0, "S")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem48_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem48.Click
        fMRIVolume.Matrix.InsertSlice(1, "S")
        UpdatefMRIVolume(fMRIVolume, "fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem51_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem51.Click
        PerfusionVolume.MatrixD.InsertSlice(0, "T")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem52_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem52.Click
        PerfusionVolume.MatrixD.InsertSlice(1, "T")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem54_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem54.Click
        PerfusionVolume.MatrixD.InsertSlice(0, "C")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem55_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem55.Click
        PerfusionVolume.MatrixD.InsertSlice(1, "C")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem57_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem57.Click
        PerfusionVolume.MatrixD.InsertSlice(0, "S")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem58_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem58.Click
        PerfusionVolume.MatrixD.InsertSlice(1, "S")
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion", False, True)
    End Sub
#End Region

    Private Sub ManualRegistrationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManualRegistrationToolStripMenuItem.Click
        Dim a, b, c, d As New Coordinate(0, 0, 0)
        Dim temp, temp2() As String

        If AnatomyVolume.Matrix IsNot Nothing Then
            Dim test As InputBoxResult = InputBox.Show("Enter Anatomy Coordinate (xx,xx,xx) : ", "Anatomy", "0,0,0")
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp = test.Text
            Else
                Exit Sub
            End If
            temp2 = temp.Split(CChar(","))
            a = New Coordinate(CInt(temp2(0)), CInt(temp2(1)), CInt(temp2(2)))
        Else
            MsgBox("Anatomy data is needed!", MsgBoxStyle.Critical)
            Exit Sub
        End If

        If FAVolume.MatrixD IsNot Nothing Then
            Dim test As InputBoxResult = InputBox.Show("Enter FA Coordinate (xx,xx,xx) : ", "FA", "0,0,0")
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp2 = test.Text.Split(CChar(","))
            Else
                Exit Sub
            End If
            b = New Coordinate(CInt(temp2(0)), CInt(temp2(1)), CInt(temp2(2)))
        End If

        If fMRIVolume.Matrix IsNot Nothing Then
            Dim test As InputBoxResult = InputBox.Show("Enter fMRI Coordinate (xx,xx,xx) : ", "fMRI", "0,0,0")
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp2 = test.Text.Split(CChar(","))
            Else
                Exit Sub
            End If
            c = New Coordinate(CInt(temp2(0)), CInt(temp2(1)), CInt(temp2(2)))
        End If

        If PerfusionVolume.MatrixD IsNot Nothing Then
            Dim test As InputBoxResult = InputBox.Show("Enter Perfusion Coordinate (xx,xx,xx) : ", "Perfusion", "0,0,0")
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                temp2 = test.Text.Split(CChar(","))
            Else
                Exit Sub
            End If
            d = New Coordinate(CInt(temp2(0)), CInt(temp2(1)), CInt(temp2(2)))
        End If
    End Sub

    Private Sub CSFMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CSFMapToolStripMenuItem.Click
        Dim CSF_AD_Cutoff As Double
        Dim CSF_FA_Cutoff As Double

        Dim test As InputBoxResult = InputBox.Show("Enter segmentation thresholds (AD,FA): ", "Thresholds", "3,0.3")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        CSF_AD_Cutoff = CDbl(temp(0))
        CSF_FA_Cutoff = CDbl(temp(1))

        Dim WM, GM, CSF As New Matrix3DSingle(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)

        Dim a, b, c As Integer

        Dim trace As Double

        For i As Integer = 0 To FAVolume.MatrixD.x - 1
            For j As Integer = 0 To FAVolume.MatrixD.y - 1
                For k As Integer = 0 To FAVolume.MatrixD.z - 1
                    trace = DTIClass.ReturnAD.data(i, j, k)

                    If trace > CSF_AD_Cutoff And FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        a += 1
                        CSF(i, j, k) = FAVolume.MatrixD(i, j, k)
                        WM(i, j, k) = 0
                        GM(i, j, k) = 0
                    ElseIf FAVolume.MatrixD(i, j, k) >= CSF_FA_Cutoff Then
                        b += 1
                        CSF(i, j, k) = 0
                        GM(i, j, k) = 0
                        WM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    ElseIf FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        c += 1
                        WM(i, j, k) = 0
                        CSF(i, j, k) = 0
                        GM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    End If
                Next
            Next
        Next

        If a > 0 Then UpdateDWIVolume(New SingleVolume(CSF, FAVolume.FOV, FAVolume.Center), "CSF", False, True)
        If b > 0 Then UpdateDWIVolume(New SingleVolume(WM, FAVolume.FOV, FAVolume.Center), "White Matter", False, True)
        If c > 0 Then UpdateDWIVolume(New SingleVolume(GM, FAVolume.FOV, FAVolume.Center), "Grey Matter", False, True)
    End Sub

    Private Sub ToolStripMenuItem63_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem63.Click
        Dim resizer As New MatrixResizer.MatrixResize
        PerfusionVolume.MatrixD = resizer.Resize(PerfusionVolume.MatrixD, PerfusionVolume.FOV.x, PerfusionVolume.FOV.y, PerfusionVolume.FOV.z)
        PerfusionVolume.Matrix = resizer.Resize(PerfusionVolume.Matrix, PerfusionVolume.FOV.x, PerfusionVolume.FOV.y, PerfusionVolume.FOV.z * 2)
        UpdatePerfusionVolume(PerfusionVolume, "Resized Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem64_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem64.Click
        Dim resizer As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation
        PerfusionVolume.MatrixD = resizer.ResizeVolumes(PerfusionVolume.MatrixD, PerfusionVolume.Center, AnatomyVolume.Center, PerfusionVolume.FOV, AnatomyVolume.FOV)
        UpdatePerfusionVolume(PerfusionVolume, "Matched Perfusion", False, True)
    End Sub

    Private Sub ToolStripMenuItem65_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem65.Click
        Dim resizer As New MatrixResizer.MatrixResize
        fMRIVolume.Matrix = resizer.Resize(fMRIVolume.Matrix, fMRIVolume.FOV.x, fMRIVolume.FOV.y, fMRIVolume.FOV.z)
        UpdatefMRIVolume(fMRIVolume, "Matched fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem66_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem66.Click
        Dim resizer As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation
        fMRIVolume.Matrix = resizer.ResizeVolumes(fMRIVolume.Matrix, fMRIVolume.Center, AnatomyVolume.Center, fMRIVolume.FOV, AnatomyVolume.FOV)
        UpdatefMRIVolume(fMRIVolume, "Matched fMRI", True, False)
    End Sub

    Private Sub ToolStripMenuItem69_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem69.Click
        If MsgBox("Oldway?", MsgBoxStyle.YesNo, "Choice") = MsgBoxResult.Yes Then
            UpdateDWIVolume(New SingleVolume(New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(0)), DiffusionVolume.FOV, DiffusionVolume.Center), "Thresholded DWI", True, False)
            Dim reversible As Boolean
            If MsgBox("Do you want this filter to be reversible?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                reversible = True
            Else
                reversible = False
            End If


            Dim temps As String

            temps = (InputBox.Show("Enter Minimum threshold (%)", "Minimum", "1").Text)
            If (temps = "") Then
                MsgBox("Action cancelled!", MsgBoxStyle.OkOnly, "Cancelled")
                Exit Sub
            End If
            Dim threshold As Integer = CInt(CInt(temps) * (DiffusionVolume.Matrix.Maximum - DiffusionVolume.Matrix.Minimum) / 100)

            temps = (InputBox.Show("Enter Maximum threshold (%)", "Maximum", "40").Text)
            If (temps = "") Then
                MsgBox("Action cancelled!", MsgBoxStyle.OkOnly, "Cancelled")
                Exit Sub
            End If

            Dim threshold2 As Integer = CInt(CInt(temps) * (DiffusionVolume.Matrix.Maximum - DiffusionVolume.Matrix.Minimum) / 100)

            Dim temp As New Matrix4DInt16(DiffusionVolume.Matrix.data)

            For i As Integer = 0 To temp.i - 1
                For j As Integer = 0 To temp.j - 1
                    For k As Integer = 0 To temp.k - 1
                        For l As Integer = 0 To temp.l - 1
                            If DiffusionVolume.Matrix.data(i, j, k, l) <= threshold Then
                                If Not reversible Then DiffusionVolume.Matrix.data(i, j, k, l) = 0
                                If reversible Then temp.data(i, j, k, l) = CShort(threshold)
                            Else
                                If reversible Then temp.data(i, j, k, l) = DiffusionVolume.Matrix.data(i, j, k, l)
                            End If
                            If DiffusionVolume.Matrix.data(i, j, k, l) >= threshold2 Then
                                If Not reversible Then DiffusionVolume.Matrix.data(i, j, k, l) = CShort(threshold2)
                                If reversible Then temp.data(i, j, k, l) = CShort(threshold2)
                            Else
                                If reversible Then temp.data(i, j, k, l) = DiffusionVolume.Matrix.data(i, j, k, l)
                            End If

                        Next
                    Next
                Next
            Next

            If reversible Then UpdateDWIVolume(New SingleVolume(New Matrix3DInt16(temp.ExtractVolume(0)), DiffusionVolume.FOV, DiffusionVolume.Center), "Thresholded DWI", True, False)
            If Not reversible Then UpdateDWIVolume(New SingleVolume(New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(0)), DiffusionVolume.FOV, DiffusionVolume.Center), "Masked DWI", True, False)
        Else
            If DiffusionVolume.Matrix IsNot Nothing Then
                Dim DTIDirectionMapViewer As New DWICorrection()
                DTIDirectionMapViewer.Show()
                DTIDirectionMapViewer.Text = "DWI Noise Removal"
                DTIDirectionMapViewer.ShowInTaskbar = True
            End If
        End If


    End Sub

    Private Sub ToolStripMenuItem70_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem70.Click

        Dim a As InputBoxResult = InputBox.Show("Choose Leveling Options: " & _
                                        vbNewLine & " 1) Constrast Stretching (Normalization)" & _
                                        vbNewLine & " 2) Histogram Equalization" & _
                                        vbNewLine & _
                                        vbNewLine & "For 1), please provide the intensity cutoff percentile, e.g. 75." & _
                                        vbNewLine & "For 2), please provide the histogram cutoff percentile, e.g. 5.", "Parameters", "2,5")
        If a.ReturnCode = Windows.Forms.DialogResult.OK Then
            If CInt(a.Text.Split(CChar(","))(0)) = 2 Then
                If Me.AnatomyVolume IsNot Nothing Then
                    AnatomyVolume.Matrix = AnatomyVolume.Matrix.MidSliceContrastStretch(CInt(a.Text.Split(CChar(","))(1)))
                    UpdateAnatomyVolume(AnatomyVolume, "Leveled Anatomy", True, False)
                End If
            ElseIf CInt(a.Text.Split(CChar(","))(0)) = 1 Then

                Dim reversible As Boolean
                If MsgBox("Do you want this filter to be reversible?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    reversible = True
                Else
                    reversible = False
                End If

                Dim threshold As Integer
                threshold = CInt((100 - CInt(a.Text.Split(CChar(","))(1))) * (AnatomyVolume.Matrix.Maximum - AnatomyVolume.Matrix.Minimum) / 100)
                Dim temp As New Matrix3DInt16(AnatomyVolume.Matrix.x, AnatomyVolume.Matrix.y, AnatomyVolume.Matrix.z)
                For i As Integer = 0 To AnatomyVolume.Matrix.x - 1
                    For j As Integer = 0 To AnatomyVolume.Matrix.y - 1
                        For k As Integer = 0 To AnatomyVolume.Matrix.z - 1
                            If AnatomyVolume.Matrix(i, j, k) > threshold Then
                                If Not reversible Then AnatomyVolume.Matrix(i, j, k) = CShort(threshold)
                                If reversible Then temp(i, j, k) = CShort(threshold)
                            Else
                                If reversible Then temp(i, j, k) = AnatomyVolume.Matrix(i, j, k)
                            End If
                        Next
                    Next
                Next
                If reversible Then UpdateAnatomyVolume(New SingleVolume(temp, AnatomyVolume.FOV, AnatomyVolume.Center), "Thresholded Anatomy", True, False)
                If Not reversible Then UpdateAnatomyVolume(AnatomyVolume, "Masked Anatomy", True, False)
            End If
        End If
    End Sub

    Private Sub SaveToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'save AD
        If DTIClass IsNot Nothing Then
            Dim tempVolume As New SingleVolume
            tempVolume.Matrix = FAVolume.Matrix
            tempVolume.MatrixD = DTIClass.ReturnAD
            tempVolume.FOV = FAVolume.FOV
            tempVolume.Center = FAVolume.Center
            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempVolume)
            MsgBox("Done!")
        End If
    End Sub

    Private Sub SaveCSFToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveCSFToolStripMenuItem.Click
        'save csf
        Dim CSF_AD_Cutoff As Double
        Dim CSF_FA_Cutoff As Double

        Dim test As InputBoxResult = InputBox.Show("Enter segmentation thresholds (AD,FA): ", "Thresholds", "3,0.3")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        CSF_AD_Cutoff = CDbl(temp(0))
        CSF_FA_Cutoff = CDbl(temp(1))

        Dim WM, GM, CSF As New Matrix3DSingle(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)

        Dim a, b, c As Integer

        Dim trace As Double

        For i As Integer = 0 To FAVolume.MatrixD.x - 1
            For j As Integer = 0 To FAVolume.MatrixD.y - 1
                For k As Integer = 0 To FAVolume.MatrixD.z - 1
                    trace = DTIClass.ReturnAD(i, j, k)

                    If trace > CSF_AD_Cutoff And FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        a += 1
                        CSF(i, j, k) = FAVolume.MatrixD(i, j, k)
                        WM(i, j, k) = 0
                        GM(i, j, k) = 0
                    ElseIf FAVolume.MatrixD(i, j, k) >= CSF_FA_Cutoff Then
                        b += 1
                        CSF(i, j, k) = 0
                        GM(i, j, k) = 0
                        WM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    ElseIf FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        c += 1
                        WM(i, j, k) = 0
                        CSF(i, j, k) = 0
                        GM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    End If
                Next
            Next
        Next

        If a > 0 Then
            Dim tempVolume As New SingleVolume
            tempVolume.MatrixD = CSF
            tempVolume.FOV = FAVolume.FOV
            tempVolume.Center = FAVolume.Center
            tempVolume.Matrix = FAVolume.Matrix
            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempVolume)

            MsgBox("Done!")
            UpdateDWIVolume(tempVolume, "CSF", False, True)
        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        'save wm
        Dim CSF_AD_Cutoff As Double
        Dim CSF_FA_Cutoff As Double

        Dim test As InputBoxResult = InputBox.Show("Enter segmentation thresholds (AD,FA): ", "Thresholds", "3,0.3")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        CSF_AD_Cutoff = CDbl(temp(0))
        CSF_FA_Cutoff = CDbl(temp(1))

        Dim WM, GM, CSF As New Matrix3DSingle(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)

        Dim a, b, c As Integer

        Dim trace As Double

        For i As Integer = 0 To FAVolume.MatrixD.x - 1
            For j As Integer = 0 To FAVolume.MatrixD.y - 1
                For k As Integer = 0 To FAVolume.MatrixD.z - 1
                    trace = DTIClass.ReturnAD(i, j, k)

                    If trace > CSF_AD_Cutoff And FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        a += 1
                        CSF(i, j, k) = FAVolume.MatrixD(i, j, k)
                        WM(i, j, k) = 0
                        GM(i, j, k) = 0
                    ElseIf FAVolume.MatrixD(i, j, k) >= CSF_FA_Cutoff Then
                        b += 1
                        CSF(i, j, k) = 0
                        GM(i, j, k) = 0
                        WM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    ElseIf FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        c += 1
                        WM(i, j, k) = 0
                        CSF(i, j, k) = 0
                        GM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    End If
                Next
            Next
        Next
        If b > 0 Then
            Dim tempVolume As New SingleVolume
            tempVolume.MatrixD = WM
            tempVolume.FOV = FAVolume.FOV
            tempVolume.Center = FAVolume.Center
            tempVolume.Matrix = FAVolume.Matrix
            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempVolume)

            MsgBox("Done!")
            UpdateDWIVolume(tempVolume, "White Matter", False, True)
        End If
    End Sub

    Private Sub SaveGMToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveGMToolStripMenuItem.Click

        'save gm
        Dim CSF_AD_Cutoff As Double
        Dim CSF_FA_Cutoff As Double

        Dim test As InputBoxResult = InputBox.Show("Enter segmentation thresholds (AD,FA): ", "Thresholds", "3,0.3")
        Dim temp() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            temp = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        CSF_AD_Cutoff = CDbl(temp(0))
        CSF_FA_Cutoff = CDbl(temp(1))

        Dim WM, GM, CSF As New Matrix3DSingle(FAVolume.MatrixD.x, FAVolume.MatrixD.y, FAVolume.MatrixD.z)

        Dim a, b, c As Integer

        Dim trace As Double

        For i As Integer = 0 To FAVolume.MatrixD.x - 1
            For j As Integer = 0 To FAVolume.MatrixD.y - 1
                For k As Integer = 0 To FAVolume.MatrixD.z - 1
                    trace = DTIClass.ReturnAD(i, j, k)

                    If trace > CSF_AD_Cutoff And FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        a += 1
                        CSF(i, j, k) = FAVolume.MatrixD(i, j, k)
                        WM(i, j, k) = 0
                        GM(i, j, k) = 0
                    ElseIf FAVolume.MatrixD(i, j, k) >= CSF_FA_Cutoff Then
                        b += 1
                        CSF(i, j, k) = 0
                        GM(i, j, k) = 0
                        WM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    ElseIf FAVolume.MatrixD(i, j, k) <= CSF_FA_Cutoff Then
                        c += 1
                        WM(i, j, k) = 0
                        CSF(i, j, k) = 0
                        GM(i, j, k) = FAVolume.MatrixD(i, j, k)
                    End If
                Next
            Next
        Next
        If c > 0 Then
            Dim tempVolume As New SingleVolume
            tempVolume.Matrix = FAVolume.Matrix
            tempVolume.MatrixD = GM
            tempVolume.FOV = FAVolume.FOV
            tempVolume.Center = FAVolume.Center

            Dim tempsaver As New SerializeMatrixtoXML
            tempsaver.SaveAs(tempVolume)

            MsgBox("Done!")
            UpdateDWIVolume(tempVolume, "Grey Matter", False, True)
        End If
    End Sub

    Private Sub ToolStripMenuItem71_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem71.Click
        PerfusionVolume.MatrixD = PerfusionLoader.PartitionData
        UpdatePerfusionVolume(PerfusionVolume, "Perfusion Ratio", False, True)
        AddPerfusionHandles()
    End Sub

    Private Sub ToolStripMenuItem72_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem72.Click
        UpdatePerfusionVolume(New SingleVolume(New Matrix3DInt16(PerfusionLoader.RemoveNoise), PerfusionVolume.FOV, PerfusionVolume.Center), "Cleaned Perfusion", True, False)
    End Sub

    Private Sub ToolStripMenuItem73_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem73.Click
        If PerfusionVolume.MatrixD IsNot Nothing Then

            Dim test As InputBoxResult = InputBox.Show("Enter Maximum Histogram RGB", "Maximum", "100")
            Dim max, min As Single
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                max = CSng(test.Text) * PerfusionVolume.MatrixD.Maximum / 255
            Else
                Exit Sub
            End If
            test = InputBox.Show("Enter Minimum Histogram RGB", "Minimum", "0")
            If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                min = CSng(test.Text) * PerfusionVolume.MatrixD.Minimum / 255
            Else
                Exit Sub
            End If

            For i As Integer = 0 To PerfusionVolume.MatrixD.x - 1
                For j As Integer = 0 To PerfusionVolume.MatrixD.y - 1
                    For k As Integer = 0 To PerfusionVolume.MatrixD.z - 1
                        If PerfusionVolume.MatrixD.data(i, j, k) > max Then PerfusionVolume.MatrixD(i, j, k) = max
                        If PerfusionVolume.MatrixD.data(i, j, k) < min Then PerfusionVolume.MatrixD(i, j, k) = min
                    Next
                Next
            Next
            UpdatePerfusionVolume(PerfusionVolume, "Filtered Perfusion Data", False, True)
        End If
    End Sub

    Private Sub ToolStripMenuItem74_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If MsgBox("This function will resize data from each direction" & vbNewLine & _
                  "to match the FOV. This will take longer than just " & vbNewLine & _
                  "resizing the FA, but it highly recommended if fur-" & vbNewLine & _
                  "ther analysis has to be done." & vbNewLine & _
                  "Do you wish to continue?", MsgBoxStyle.YesNo, "Resize All") = MsgBoxResult.Yes Then
            Dim resizer As New MatrixResizer.MatrixResize
            Dim tempf As New Matrix4DInt16(CInt(Math.Round(DiffusionVolume.FOV.x)), CInt(Math.Round(DiffusionVolume.FOV.y)), CInt(Math.Round(DiffusionVolume.FOV.z)), DiffusionVolume.Matrix.l - 1)
            For l As Integer = 0 To DiffusionVolume.Matrix.l - 2
                tempf.LoadVolume(l, resizer.Resize(New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(l)), DiffusionVolume.FOV.x, DiffusionVolume.FOV.y, DiffusionVolume.FOV.z).data)
            Next
            DiffusionVolume.Matrix = New Matrix4DInt16(tempf.data)
            UpdateDWIVolume(New SingleVolume(New Matrix3DInt16(DiffusionVolume.Matrix.ExtractVolume(0)), DiffusionVolume.FOV, DiffusionVolume.Center), "Resized DWI", True, False)
            Me.ToolStripMenuItem60.Enabled = False
        End If
    End Sub

    Private Sub ConvertPerfusionRatioToAbsoluteValuesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConvertPerfusionRatioToAbsoluteValuesToolStripMenuItem.Click
        If PerfusionDisplay IsNot Nothing Then
            Try
                Dim test As InputBoxResult = InputBox.Show("Enter Parameters (transit-time,delay-time): ", "Parameters", "0,0.86")
                Dim temp() As String
                If test.ReturnCode = Windows.Forms.DialogResult.OK Then
                    temp = test.Text.Split(CChar(","))
                Else
                    Exit Sub
                End If
                Dim PerfusionQuantizer As New ComputeAbsoluteMeasures(ComputeAbsoluteMeasures.ScannerTypeDefaults.ThreeTesla, CSng(temp(0)), CSng(temp(1)))
                For i As Integer = 0 To PerfusionVolume.MatrixD.x - 1
                    For j As Integer = 0 To PerfusionVolume.MatrixD.y - 1
                        For k As Integer = 0 To PerfusionVolume.MatrixD.z - 1
                            PerfusionVolume.MatrixD.data(i, j, k) = PerfusionQuantizer.ReturnCBF(PerfusionVolume.MatrixD.data(i, j, k))
                        Next
                    Next
                Next
                MsgBox("Quantization Complete. Perfusion Display now shows CBF in ml/100g/min")
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Private Sub FAWithAnatomyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FAWithAnatomyToolStripMenuItem.Click
        If FAVolume.Matrix IsNot Nothing Then
            Dim a As New RegistrationForm(AnatomyVolume.Matrix, FAVolume.Matrix)
            a.Show()
        End If
    End Sub

    Private Sub FMRIWithAnatomyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FMRIWithAnatomyToolStripMenuItem.Click
        If fMRIVolume.Matrix IsNot Nothing Then
            Dim a As New RegistrationForm(AnatomyVolume.Matrix, fMRIVolume.Matrix)
            a.Show()
        End If
    End Sub

    Private Sub PerfusionWithAnatomyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PerfusionWithAnatomyToolStripMenuItem.Click
        If PerfusionVolume.MatrixD IsNot Nothing Then
            Dim a As New RegistrationForm(AnatomyVolume.Matrix, PerfusionVolume.MatrixD)
            a.Show()
        End If
    End Sub

    Private Sub ToolStripMenuItem75_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem75.Click
        CSI.Show()
    End Sub

    Private Sub UsingDWIDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UsingDWIDataToolStripMenuItem.Click

        Dim tempFile As String = "DWIwithoutStripping"
        Dim tempFile2 As String = "StrippedDWI"
        Dim s As InputBoxResult = InputBox.Show("Enter Fractional Intensity Threshold (0 to 1) " & vbNewLine & _
                                              "and Vertical Gradient (-1 to 1): " & vbNewLine & vbNewLine & _
                                              "Note: Smaller FIT gives larger brain outline" & vbNewLine & _
                                              "estimates. Smaller VG gives larger brain outline" & vbNewLine & _
                                              "at bottom and higher VG at top.", "Parameters", "0.5,0")
        HdrImgWriter.WriteToFile(FAVolume, tempFile, DataType.DT_FLOAT)
        If s.ReturnCode = Windows.Forms.DialogResult.OK And s.Text.Contains(",") Then
            Dim command As String = "bet.exe " & tempFile & ".hdr " & tempFile2 & ".hdr -f " & s.Text.Split(CChar(","))(0) & " -g " & s.Text.Split(CChar(","))(1)
            Shell(command, AppWinStyle.Hide, True, -1)
            FAVolume.Matrix = HdrImgReader.ReadFromHdrFile(tempFile2 & ".hdr", OutPutType.int16).Matrix

            For i As Integer = 0 To FAVolume.Matrix.x - 1
                For j As Integer = 0 To FAVolume.Matrix.y - 1
                    For k As Integer = 0 To FAVolume.Matrix.z - 1
                        If FAVolume.Matrix.data(i, j, k) = 0 Then FAVolume.MatrixD.data(i, j, k) = 0
                    Next
                Next
            Next
            UpdateDWIVolume(FAVolume, "Stripped FA", False, True)
        End If
    End Sub

    Private Sub UsingAnatomyDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UsingAnatomyDataToolStripMenuItem.Click
        If MsgBox("Is Anatomy data loaded, stripped & matched with FA data? ", MsgBoxStyle.YesNo, "Skull Stripping") = MsgBoxResult.Yes Then
            If FAVolume.MatrixD.x <> AnatomyVolume.Matrix.x Or FAVolume.MatrixD.y <> AnatomyVolume.Matrix.y Or FAVolume.MatrixD.z <> AnatomyVolume.Matrix.z Then
                MsgBox("Size Mismatch!")
                Exit Sub
            End If
            For i As Integer = 0 To FAVolume.MatrixD.x - 1
                For j As Integer = 0 To FAVolume.MatrixD.y - 1
                    For k As Integer = 0 To FAVolume.MatrixD.z - 1
                        If AnatomyVolume.Matrix.data(i, j, k) = 0 Then FAVolume.MatrixD.data(i, j, k) = 0
                    Next
                Next
            Next
            UpdateDWIVolume(FAVolume, "Stripped FA", False, True)
        Else
            Exit Sub
        End If
    End Sub

    Private Sub ToolStripMenuItem79_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem79.Click
        Dim test As InputBoxResult
        test = InputBox.Show("Kernelsize & Variance (5,0.5)", "Gaussian Parameters", "5,0.5")
        Dim choice() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            choice = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        Dim a As New Gaussian3D(CInt(choice(0)), CDbl(choice(1)))
        AnatomyVolume.Matrix = a.ApplyGaussian(AnatomyVolume.Matrix)
        UpdateAnatomyVolume(AnatomyVolume, "Smoothened Anatomy", True, False)
    End Sub

    Private Sub ToolStripMenuItem80_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem80.Click
        Dim test As InputBoxResult
        test = InputBox.Show("# of iterations, Lambda & K  (100,0.16,4)", "Anisotropic Smoothing Parameters", "100,0.16,4")
        Dim choice() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            choice = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        Dim ad As New MetaViewAnisotropicDiffusion.PeronaMalik.Anisotropic(CSng(choice(1)))
        MetaViewAnisotropicDiffusion.PeronaMalik.Anisotropic.AnisotropicDiffuse(AnatomyVolume.Matrix, CInt(choice(2)), CInt(choice(0)))

        UpdateAnatomyVolume(AnatomyVolume, "Smoothened Anatomy", True, False)
    End Sub

    Private Sub ToolStripMenuItem81_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem81.Click
        Dim test As InputBoxResult
        test = InputBox.Show("# of iterations, Lambda & K (100,0.16,4)", "Anisotropic Smoothing Parameters", "100,0.16,4")
        Dim choice() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            choice = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        Dim ad As New MetaViewAnisotropicDiffusion.PeronaMalik.Anisotropic(CSng(choice(1)))
        ad.AnisoDiff3D(AnatomyVolume.Matrix, CInt(choice(2)), CInt(choice(0)))

        UpdateAnatomyVolume(AnatomyVolume, "Smoothened Anatomy", True, False)
    End Sub

    Private Sub ToolStripMenuItem82_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem82.Click
        Dim test As InputBoxResult
        test = InputBox.Show("# of iterations, Lambda & K (100,0.16,4)", "Anisotropic Smoothing Parameters", "100,0.16,4")
        Dim choice() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            choice = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If

        Dim ad As New MetaViewAnisotropicDiffusion.PeronaMalik.Anisotropic(CSng(choice(1)))
        ad.AnisoDiff3D(FAVolume.MatrixD, CInt(choice(2)), CInt(choice(0)))
        UpdateDWIVolume(FAVolume, "Smoothened FA", False, True)

    End Sub

    Private Sub ToolStripMenuItem83_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem83.Click
        'Inhomogenity Correction for Anatomy
        Dim a As New InhomogenityCorrection(AnatomyVolume.Matrix)
        a.Show()
    End Sub

    Dim wc, wc2 As WindowContent
    Private Sub RestoreOriginalWindowzToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestoreOriginalWindowzToolStripMenuItem.Click
        _dockingmanager.Contents.Clear()
        Dim perfusioncontainer As Content = _dockingmanager.Contents.Add(PerfusionDisplay, "Perfusion Data", _internalimages, 1)
        Dim diffusioncontainer As Content = _dockingmanager.Contents.Add(DiffusionDisplay, "DWI/DTI Data", _internalimages, 1)
        Dim fmricontainer As Content = _dockingmanager.Contents.Add(fMRIDisplay, "fMRI Data", _internalimages, 1)
        Dim anatomycontainer As Content = _dockingmanager.Contents.Add(AnatomyDisplay, "Anatomy Data", _internalimages, 1)
        perfusioncontainer.DisplaySize = CommonWindowSize
        diffusioncontainer.DisplaySize = CommonWindowSize
        fmricontainer.DisplaySize = CommonWindowSize
        anatomycontainer.DisplaySize = CommonWindowSize

        wc = _dockingmanager.AddContentWithState(perfusioncontainer, State.DockRight)
        _dockingmanager.AddContentToZone(diffusioncontainer, wc.ParentZone, 0)

        wc2 = _dockingmanager.AddContentWithState(fmricontainer, State.DockLeft)
        _dockingmanager.AddContentToZone(anatomycontainer, wc2.ParentZone, 0)


        _dockingmanager.InnerControl = Nothing
        _dockingmanager.InsideFill = True

    End Sub

    Private Sub ToolStripMenuItem84_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem84.Click
        TalairachTransformationChoose.Show()
    End Sub


    Private Sub ToolStripMenuItem86_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem86.Click
        Dim a As New MagnifierForm
        a.Show()

    End Sub

    Private Sub ToolStripMenuItem87_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem87.Click
        RuntimeObjectEditor.ObjectEditor.Instance.Enable()
        RuntimeObjectEditor.ObjectEditor.Instance.Show()
    End Sub

    Private Sub ToolStripMenuItem92_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem92.Click
        Dim a As New FiberTrackingView
        a.Show()
    End Sub

#Region "Refresh / Open DataSets"
    Private Sub ToolStripMenuItem95_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem95.Click
        'open dwi
        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "Philips Header file (*.par)|*.par|Analyze Header file (*.hdr)|*.hdr|All files (*.*)|*.*"
        ofd.Title = "Choose the DWI Dataset file"
        Dim params(2) As String

        params(0) = "dwi".ToLower()
        If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
            params(1) = ofd.FileName
            BackgroundWorker1.RunWorkerAsync(params)
            BusyDialog.ShowDialog(Me)
        End If
    End Sub
    Private Sub ToolStripMenuItem96_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem96.Click
        'open fmri
        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "SPM Header file (*.hdr)|*.hdr|SPM Image file (*.img)|*.img|All files (*.*)|*.*"
        ofd.Title = "Choose the SPM T-Map Dataset Header file"
        Dim params(2) As String
        params(0) = "fmri".ToLower()

        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            params(1) = ofd.FileName
            BackgroundWorker1.RunWorkerAsync(params)
            BusyDialog.ShowDialog(Me)
        End If
    End Sub
    Private Sub ToolStripMenuItem97_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem97.Click
        'perfusion
        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "Philips Header file (*.par)|*.par|Philips Image file (*.rec)|*.rec|All files (*.*)|*.*"

        ofd.Title = "Choose the Perfusion Dataset Header file"
        Dim params(2) As String
        params(0) = "perfusion".ToLower()

        If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
            params(1) = ofd.FileName
            BackgroundWorker1.RunWorkerAsync(params)
            BusyDialog.ShowDialog(Me)
        End If
    End Sub
    Private Sub ToolStripMenuItem98_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem98.Click
        'open anatomy
        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "Philips Header file (*.par)|*.par|Analyze Header file (*.hdr)|*.hdr|All files (*.*)|*.*"
        ofd.Title = "Choose the Anatomy Dataset file"
        Dim params(2) As String
        params(0) = "anatomy".ToLower()

        If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
            params(1) = ofd.FileName
            BackgroundWorker1.RunWorkerAsync(params)
            BusyDialog.ShowDialog(Me)
        End If
    End Sub
#End Region

    Private Sub CustomSizeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomSizeToolStripMenuItem.Click
        Dim c(3) As String
        Dim test As InputBoxResult = InputBox.Show("Enter size (xx,xx,xx): ", "Size", AnatomyVolume.FOV.x & "," & AnatomyVolume.FOV.y & "," & AnatomyVolume.FOV.z)
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            c = test.Text.Split(CChar(","))
            If CDbl(c(0)) <= 0 Or CDbl(c(1)) <= 0 Or CDbl(c(2)) <= 0 Then Exit Sub
        Else
            Exit Sub
        End If

        Dim resizer As New MatrixResizer.MatrixResize
        AnatomyVolume.Matrix = resizer.Resize(AnatomyVolume.Matrix, CInt(c(0)), CInt(c(1)), CInt(c(2)))
        AnatomyVolume.FOV.x = CShort(c(0))
        AnatomyVolume.FOV.y = CShort(c(1))
        AnatomyVolume.FOV.z = CShort(c(2))

        UpdateAnatomyVolume(AnatomyVolume, "Resized Anatomy", True, False)
    End Sub

    Private Sub MenuStrip1_MenuActivate(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuStrip1.MenuActivate
        GC.Collect()
    End Sub

#Region "Anatomy Filters"
    Private Sub ToolStripMenuItem67_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem67.Click
        Dim test As InputBoxResult
        test = InputBox.Show("Enter Min, Max", "Resampling Parameters", "500,0")
        Dim choice() As String
        If test.ReturnCode = Windows.Forms.DialogResult.OK Then
            choice = test.Text.Split(CChar(","))
        Else
            Exit Sub
        End If
        Dim max As Integer = CInt(choice(1))
        Dim min As Integer = CInt(choice(0))
        Dim oldmin As Integer = AnatomyVolume.Matrix.Minimum
        Dim oldmax As Integer = AnatomyVolume.Matrix.Maximum
        For i As Integer = 0 To AnatomyVolume.Matrix.x - 1
            For j As Integer = 0 To AnatomyVolume.Matrix.y - 1
                For k As Integer = 0 To AnatomyVolume.Matrix.z - 1
                    AnatomyVolume.Matrix(i, j, k) = CShort((AnatomyVolume.Matrix(i, j, k) - oldmin) * (max - min) / (oldmax - oldmin) + min)
                Next
            Next
        Next
        UpdateAnatomyVolume(AnatomyVolume, "Scaled Data", True, False)
    End Sub
    Private Sub FOVIsovoxelTransformToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FOVIsovoxelTransformToolStripMenuItem.Click
        Dim resizer As New MatrixResizer.MatrixResize
        AnatomyVolume.Matrix = resizer.Resize(AnatomyVolume.Matrix, AnatomyVolume.FOV.x, AnatomyVolume.FOV.y, AnatomyVolume.FOV.z)
        UpdateAnatomyVolume(AnatomyVolume, "Resized Anatomy", True, False)
    End Sub
    Private Sub ToolStripMenuItem99_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem99.Click
        AIRbasedRegistration.Show()
    End Sub
    Private Sub ToolStripMenuItem100_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem100.Click
        FSL_Fast.Show()
    End Sub
    Private Sub IntensityCroppingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IntensityCroppingToolStripMenuItem.Click
        'intensity
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim min As Single = CSng(InputBox.Show("Enter Minimum value", "Minimum", "10").Text)
            Dim max As Single = CSng(InputBox.Show("Enter Maximum value", "Maximum", "1000").Text)
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\imagefilter.exe" & Chr(34) & " -nointer -min " & min & " -max " & max & " -extract"
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Analyze (*.hdr)|*.hdr"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub WeinerFilterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WeinerFilterToolStripMenuItem.Click
        'weiner
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim noise As Single = CSng(InputBox.Show("Enter Noise Variance:", "Noise", "5").Text)
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\imagefilter.exe" & Chr(34) & " -type wiener -noise " & noise
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Analyze (*.hdr)|*.hdr"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub MedianFileterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MedianFileterToolStripMenuItem.Click
        'median
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim iter As Integer = CInt(InputBox.Show("Enter Iterations", "Iterations", "10").Text)
            Dim conn As String = InputBox.Show("Enter Connectivity (c6/c18/c26)", "Connectivity", "c6").Text
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\imagefilter.exe" & Chr(34) & "  -type median -conn " & conn & " -iter " & iter
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Analyze (*.hdr)|*.hdr"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub AnisotropicSmootingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AnisotropicSmootingToolStripMenuItem.Click
        'anisotropic smoothing
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim scale As Single = CSng(InputBox.Show("Enter Scale Parameter", "Scale", "1").Text)
            Dim norm As Single = CSng(InputBox.Show("Enter Rescale Maximum", "Max", "100").Text)
            Dim param As Int16 = CShort(InputBox.Show("Enter Anisotropic Diffusion Filter strength parameter", "Strength", "2").Text)
            Dim iter As Integer = CInt(InputBox.Show("Enter Iterations", "Iterations", "10").Text)
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\imagediffuse.exe" & Chr(34) & " -scale " & scale & " -norm " & norm & " -m26 -k " & param & " -it " & iter
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Analyze (*.hdr)|*.hdr"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub MorphometricMaskingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MorphometricMaskingToolStripMenuItem.Click
        Dim DTIDirectionMapViewer As New DWICorrection()
        DTIDirectionMapViewer.Show()
        DTIDirectionMapViewer.Text = "DWI Noise Removal"
        DTIDirectionMapViewer.ShowInTaskbar = True

    End Sub
    Private Sub ToolStripMenuItem102_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem102.Click
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim low As Single = CSng(InputBox.Show("Enter Low Parameter", "Low", "1").Text)
            Dim high As Single = CSng(InputBox.Show("Enter High Parameter", "High", "100").Text)
            Dim iter As Integer = CInt(InputBox.Show("Enter Iterations", "Iterations", "10").Text)
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\image2surf.exe" & Chr(34) & " -it " & iter & " -sw 1 -lo " & low & " -hi " & high
            Dim sfd As New SaveFileDialog
            sfd.Filter = "OOGL File (*.*)|*.*"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem103_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem103.Click
        Dim ofd1 As New OpenFileDialog
        ofd1.Filter = "Analyze (*.hdr)|*.hdr"
        ofd1.Title = "Choose the file"
        If ofd1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim scale As Single = CSng(InputBox.Show("Enter Scale Parameter", "Scale", "1").Text)
            Dim norm As Single = CSng(InputBox.Show("Enter Rescale Maximum", "Max", "100").Text)
            Dim param As Int16 = CShort(InputBox.Show("Enter Anisotropic Diffusion Filter strength parameter", "Strength", "2").Text)
            Dim iter As Integer = CInt(InputBox.Show("Enter Iterations", "Iterations", "10").Text)
            Dim command As String = Chr(34) & My.Application.Info.DirectoryPath & "\imagediffuse.exe" & Chr(34) & " -scale " & scale & " -norm " & norm & " -m26 -k " & param & " -it " & iter
            Dim sfd As New SaveFileDialog
            sfd.Filter = "Analyze (*.hdr)|*.hdr"
            sfd.Title = "Save As.."
            If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
                command = command & " " & Chr(34) & ofd1.FileName & Chr(34) & " " & Chr(34) & sfd.FileName & Chr(34)
                MsgBox("Executing: " & command)
                Dim ex As New ShellClass
                ex.UseNewThread = True
                ex.CaptureOutput = True
                ex.CaptureError = True
                ex.Execute(command)
                MsgBox(ex.Output)
            End If
        End If
    End Sub
    Private Sub ToolStripMenuItem76_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem76.Click
        Dim s As String = InputBox.Show("Enter Fractional Intensity Threshold (0 to 1) " & vbNewLine & _
                                              "and Vertical Gradient (-1 to 1): " & vbNewLine & vbNewLine & _
                                              "Note: Smaller FIT gives larger brain outline" & vbNewLine & _
                                              "estimates. Smaller VG gives larger brain outline" & vbNewLine & _
                                              "at bottom and higher VG at top.", "Parameters", "0.5,0").Text
        Dim fname As String = System.IO.Path.GetTempFileName.Replace(".tmp", "")
        Dim tempFile As String = fname & "_old"
        Dim tempFile2 As String = fname & "_stripped"
        HdrImgWriter.WriteToFile(AnatomyVolume, tempFile)

        Dim command As String = ControlChars.Quote & My.Application.Info.DirectoryPath & "\" & "bet.exe" & ControlChars.Quote & " " & ControlChars.Quote & tempFile & ".hdr" & ControlChars.Quote + " " & ControlChars.Quote & tempFile2 & ".hdr" & ControlChars.Quote & " -f " & s.Split(CChar(","))(0) & " -g " & s.Split(CChar(","))(1)
        Try
            Shell(command, AppWinStyle.NormalFocus, True)
            AnatomyVolume.Matrix = HdrImgReader.ReadFromHdrFile(tempFile2 & ".hdr", OutPutType.int16).Matrix
        Catch ex As Exception
            MsgBox("Execution Failed - " + vbNewLine + command)
        End Try
        UpdateAnatomyVolume(AnatomyVolume, "Stripped Anatomy", True, False)
    End Sub
    Private Sub ToolStripMenuItem78_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem78.Click
        Dim SF As New SegmentationForm(AnatomyDisplay.CurrentImage(False), 128, 0)
        SF.Show()
    End Sub
    Private Sub SPARFileVOIToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SPARFileVOIToolStripMenuItem.Click
        MessageBox.Show("This option has been outdated. Please use " & vbNewLine & _
                        "the command line utility SparFilter.exe to" & vbNewLine & _
                        "perform this task." & vbNewLine & _
                        "Usage: SparFilter.exe SPARPATH HDRPATH [PARPATH]")
    End Sub
    Private Function ToAbsoluteCoordinate(ByVal myMatrixCoordinate As Coordinate, ByVal myfov As Coordinate, ByVal myrealcenter As Coordinate) As Coordinate
        Return New Coordinate(myrealcenter.x - CInt(myfov.x / 2) + myMatrixCoordinate.x, _
myrealcenter.y - CInt(myfov.y / 2) + myMatrixCoordinate.y, _
myrealcenter.z - CInt(myfov.z / 2) + myMatrixCoordinate.z)
    End Function
    Private Function ToMatrixCoordinate(ByVal myAbsoluteCoordinate As Coordinate, ByVal myfov As Coordinate, ByVal myrealcenter As Coordinate) As Coordinate
        Return New Coordinate(-1 * myrealcenter.x + CInt(myfov.x / 2) + myAbsoluteCoordinate.x, _
-1 * myrealcenter.y + CInt(myfov.y / 2) + myAbsoluteCoordinate.y, _
-1 * myrealcenter.z + CInt(myfov.z / 2) + myAbsoluteCoordinate.z)
    End Function
#End Region

    Private Sub IntensityMaskPerfusionMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IntensityMaskPerfusionMapToolStripMenuItem.Click
        Dim IntMask As New ThresholdMaskApplicator(PerfusionVolume.MatrixD, PerfusionVolume.Matrix)
        UpdatePerfusionVolume(New SingleVolume(IntMask.ReturnThresholdded3, PerfusionVolume), "Perfusion", True, True)
    End Sub

#Region "BackGroundWorker Threads"

    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        Dim params() As String = CType(e.Argument, String())
        Select Case params(0)
            Case "anatomy"
                NewAnatomyVolumeLoader(params(1))
            Case "dwi"
                NewDWIVolumeLoader(params(1))
            Case "fmri"
                NewFMRIVolumeLoader(params(1))
            Case "perfusion"
                NewPerfusionVolumeLoader(params(1))
        End Select

    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        Me.MenuStrip1.Enabled = False
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        BusyDialog.Close()
        Me.MenuStrip1.Enabled = True
        If e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message)
        End If
        If e.Cancelled Then
            MessageBox.Show("The task was successfully cancelled.")
        End If
    End Sub

#End Region

    Private Sub DWIToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DWIToolStripMenuItem.Click
        'Match Anatomy coordinates to DWI
        If DiffusionVolume IsNot Nothing Then
            Dim resizerObj As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation
            AnatomyVolume.Matrix = resizerObj.ResizeVolumes(AnatomyVolume.Matrix, AnatomyVolume.Center, DiffusionVolume.Center, AnatomyVolume.FOV, DiffusionVolume.FOV)
            AnatomyVolume.Center = DiffusionVolume.Center
            AnatomyVolume.FOV = DiffusionVolume.FOV
            UpdateAnatomyVolume(AnatomyVolume, "Matched Anatomy", True, False)
        End If
    End Sub

    Private Sub CustomToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomToolStripMenuItem.Click
        Dim fov As New CoordinateD(0, 0, 0)
        If MessageBox.Show("Do you want to sample the matrix size?", "Question", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
            Dim result() As String = InputBox.Show("Enter Size (x,y,z)", "Size", "128,128,96").Text.Split(CChar(","))
            fov = New CoordinateD(CInt(result(0)), CInt(result(1)), CInt(result(2)))
        Else
            fov = AnatomyVolume.FOV
        End If
        Dim center As New CoordinateD(0, 0, 0)
        If MessageBox.Show("Do you want to change the matrix origin?", "Question", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
            Dim result() As String = InputBox.Show("Enter origin (x,y,z)", "Size", "128,128,96").Text.Split(CChar(","))
            center = New CoordinateD(Double.Parse(result(0)), Double.Parse(result(1)), Double.Parse(result(2)))
        Else
            center = AnatomyVolume.Center
        End If

        Dim resizerObj As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation
        AnatomyVolume.Matrix = resizerObj.ResizeVolumes(AnatomyVolume.Matrix, AnatomyVolume.Center, center, AnatomyVolume.FOV, fov)
        UpdateAnatomyVolume(AnatomyVolume, "ReSampled Anatomy", True, False)
    End Sub

    Private Sub ToolStripMenuItem105_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem105.Click
        If DTIClass IsNot Nothing Then
            Dim usedOldWay As Boolean = False
            usedOldWay = DTIClass.ReturnEigenValue(3) Is Nothing

            Dim resizer As New MatrixResizer.MatrixResize
            Dim resizer2 As New MatrixDataStructures.BasicPixelSizeMatrixInterpolation

            Dim tempvolume As New SingleVolume

            tempvolume.FOV = DiffusionVolume.FOV
            tempvolume.Center = DiffusionVolume.Center

            If usedOldWay Then
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Small)
            Else
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(1)
            End If
            tempvolume.MatrixD = resizer.Resize(tempvolume.MatrixD, tempvolume.FOV.x, tempvolume.FOV.y, tempvolume.FOV.z)
            tempvolume.MatrixD = resizer2.ResizeVolumes(tempvolume.MatrixD, tempvolume.Center, AnatomyVolume.Center, tempvolume.FOV, AnatomyVolume.FOV)
            UpdateDWIVolume(tempvolume, "L1", False, True)

            If usedOldWay Then
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Medium)
            Else
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(2)
            End If
            tempvolume.MatrixD = resizer.Resize(tempvolume.MatrixD, tempvolume.FOV.x, tempvolume.FOV.y, tempvolume.FOV.z)
            tempvolume.MatrixD = resizer2.ResizeVolumes(tempvolume.MatrixD, tempvolume.Center, AnatomyVolume.Center, tempvolume.FOV, AnatomyVolume.FOV)
            UpdateDWIVolume(tempvolume, "L2", False, True)

            If usedOldWay Then
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(ComputeDTI.Order.Big)
            Else
                tempvolume.MatrixD = DTIClass.ReturnEigenValue(3)
            End If
            tempvolume.MatrixD = resizer.Resize(tempvolume.MatrixD, tempvolume.FOV.x, tempvolume.FOV.y, tempvolume.FOV.z)
            tempvolume.MatrixD = resizer2.ResizeVolumes(tempvolume.MatrixD, tempvolume.Center, AnatomyVolume.Center, tempvolume.FOV, AnatomyVolume.FOV)
            UpdateDWIVolume(tempvolume, "L3", False, True)

            FAVolume.FOV = DiffusionVolume.FOV
            FAVolume.MatrixD = resizer.Resize(FAVolume.MatrixD, FAVolume.FOV.x, FAVolume.FOV.y, FAVolume.FOV.z)
            FAVolume.MatrixD = resizer2.ResizeVolumes(FAVolume.MatrixD, FAVolume.Center, AnatomyVolume.Center, FAVolume.FOV, AnatomyVolume.FOV)
            FAVolume.Center = AnatomyVolume.Center
            FAVolume.FOV = AnatomyVolume.FOV
            UpdateDWIVolume(FAVolume, "FA", False, True)
            If MessageBox.Show("In addition to displaying FA, do you want to save FA data as float?", "FA", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                Dim saveDlg As SaveFileDialog = New SaveFileDialog
                Dim dlgResult As DialogResult = New DialogResult

                'Set the filter to JPEG files only.
                saveDlg.Filter = "Analyze Header Files (*.hdr)|*.hdr"
                saveDlg.Title = "Select the file to save the header to.."

                dlgResult = CType(saveDlg.ShowDialog, Windows.Forms.DialogResult)

                If dlgResult = Windows.Forms.DialogResult.OK Then
                    HdrImgWriter.WriteToFile(FAVolume, saveDlg.FileName, DataType.DT_FLOAT)
                End If
            End If
        End If
    End Sub

    Private Sub FSLSegmentationResultToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FSLSegmentationResultToolStripMenuItem.Click
        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "Analyze Header file (*.hdr)|*.hdr|All files (*.*)|*.*"
        ofd.Title = "Choose the Segmentation Result file"
        Dim params(2) As String

        If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim fname As New System.IO.FileInfo(ofd.FileName)
            Dim FSLresult As New MatrixDataStructures.SingleVolume()
            FSLresult = HdrImgReader.ReadFromHdrFile(ofd.FileName, OutPutType.int16)
            FSLresult.HeaderFileName = ofd.FileName
            Dim output1, output2, output3 As New Matrix3DInt16(AnatomyVolume.Matrix.x, AnatomyVolume.Matrix.y, AnatomyVolume.Matrix.z)
            Dim count1 As Long = 0
            Dim count2 As Long = 0
            Dim count3 As Long = 0
            For i As Integer = 0 To AnatomyVolume.Matrix.x - 1
                For j As Integer = 0 To AnatomyVolume.Matrix.y - 1
                    For k As Integer = 0 To AnatomyVolume.Matrix.z - 1
                        If (FSLresult.Matrix(i, j, k) = 1) And AnatomyVolume.Matrix(i, j, k) > 0 Then
                            output1(i, j, k) = AnatomyVolume.Matrix(i, j, k)
                            count1 += 1
                        End If
                        If (FSLresult.Matrix(i, j, k) = 2) And AnatomyVolume.Matrix(i, j, k) > 0 Then
                            output2(i, j, k) = AnatomyVolume.Matrix(i, j, k)
                            count2 += 1
                        End If
                        If (FSLresult.Matrix(i, j, k) = 3) And AnatomyVolume.Matrix(i, j, k) > 0 Then
                            output3(i, j, k) = AnatomyVolume.Matrix(i, j, k)
                            count3 += 1
                        End If
                    Next
                Next
            Next
            AnatomyDisplay.OpenFile(New SingleVolume(output1, AnatomyVolume.FOV, AnatomyVolume.Center), "Tag 1", True, False)
            AnatomyDisplay.OpenFile(New SingleVolume(output2, AnatomyVolume.FOV, AnatomyVolume.Center), "Tag 2", True, False)
            AnatomyDisplay.OpenFile(New SingleVolume(output3, AnatomyVolume.FOV, AnatomyVolume.Center), "Tag 3", True, False)
            MessageBox.Show("Tag 1 count: " & count1, "Tag 1", MessageBoxButtons.OK)
            MessageBox.Show("Tag 2 count: " & count2, "Tag 2", MessageBoxButtons.OK)
            MessageBox.Show("Tag 3 count: " & count3, "Tag 3", MessageBoxButtons.OK)
        End If
    End Sub

    Private Sub AboutToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem1.Click
        If AnatomyVolume IsNot Nothing Then
            MsgBox(AnatomyVolume.ToString())
        Else
            MsgBox("Not defined.")
        End If
    End Sub

    Private Sub AppendOriginToAnalyzeFilesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AppendOriginToAnalyzeFilesToolStripMenuItem.Click

        Dim ofd As New OpenFileDialog       'open file dialog
        ofd.FileName = ""
        ofd.Filter = "Analyze Header file (*.hdr)|*.hdr"
        ofd.Title = "Choose the Analyze Dataset Header file"

        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim dataVolume As SingleVolume
            dataVolume = HdrImgReader.ReadFromHdrFile(ofd.FileName, OutPutType.int16)
            dataVolume.HeaderFileName = ofd.FileName

            Dim originInput As String = InputBox.Show("Enter Origin in the form a,b,c", "Origin", "0,0,0").Text
            Dim origin As CoordinateD = New CoordinateD(Double.Parse(originInput.Trim.Split(CChar(","))(0)), Double.Parse(originInput.Trim.Split(CChar(","))(1)), Double.Parse(originInput.Trim.Split(CChar(","))(2)))
            dataVolume.Center = origin
            Dim SFD As New Windows.Forms.SaveFileDialog
            SFD.AddExtension = False
            SFD.Title = "Save Analyze file as ..."
            SFD.Filter = "All files (*.*)|*.*"
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                HdrImgWriter.WriteToFile(dataVolume, SFD.FileName)
            End If
        End If
    End Sub

    Private Sub FormMain_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        Application.Exit()
    End Sub

    Private Sub FormMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ReleaseMemory()
    End Sub

    Private Sub ToolStripMenuItem61_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem61.Click
        AnatomyDisplay = New MainForm
        DiffusionDisplay = New MainForm
        fMRIDisplay = New MainForm
        PerfusionDisplay = New MainForm

        AnatomyVolume = Nothing
        DiffusionVolume = Nothing
        FAVolume = Nothing
        fMRIVolume = Nothing
        PerfusionVolume = Nothing
        _dockingmanager.Contents.Clear()
        Dim perfusioncontainer As Content = _dockingmanager.Contents.Add(PerfusionDisplay, "Perfusion Data", _internalimages, 1)
        Dim diffusioncontainer As Content = _dockingmanager.Contents.Add(DiffusionDisplay, "DWI/DTI Data", _internalimages, 1)
        Dim fmricontainer As Content = _dockingmanager.Contents.Add(fMRIDisplay, "fMRI Data", _internalimages, 1)
        Dim anatomycontainer As Content = _dockingmanager.Contents.Add(AnatomyDisplay, "Anatomy Data", _internalimages, 1)
        perfusioncontainer.DisplaySize = CommonWindowSize
        diffusioncontainer.DisplaySize = CommonWindowSize
        fmricontainer.DisplaySize = CommonWindowSize
        anatomycontainer.DisplaySize = CommonWindowSize

        wc = _dockingmanager.AddContentWithState(perfusioncontainer, State.DockRight)
        _dockingmanager.AddContentToZone(diffusioncontainer, wc.ParentZone, 0)

        wc2 = _dockingmanager.AddContentWithState(fmricontainer, State.DockLeft)
        _dockingmanager.AddContentToZone(anatomycontainer, wc2.ParentZone, 0)


        _dockingmanager.InnerControl = Nothing
        _dockingmanager.InsideFill = True

        ReleaseMemory()
    End Sub
End Class
